diff --git a/.gitattributes b/.gitattributes index 443c437442..72b8ab0ea9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -20,27 +20,9 @@ *.filters text eol=crlf *.vcxitems text eol=crlf - -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -#*.xproj merge=binary -#*.props merge=binary -#*.filters merge=binary -#*.vcxitems merge=binary - # C# -*.cs diff=csharp +*.cs diff=csharp +*.g.cs linguist-generated # Powershell *.ps1 text eol=crlf diff --git a/Build/Test.ps1 b/Build/Test.ps1 new file mode 100644 index 0000000000..9458d0934b --- /dev/null +++ b/Build/Test.ps1 @@ -0,0 +1,17 @@ +$root = Resolve-Path $PSScriptRoot/.. + +[int]$exitCode = 0 + +# When this change is made available, we can possibly simplify below with: `dotnet test MySolution.sln` +# Run tests only for test projects by smadala · Pull Request #1745 · Microsoft/vstest +# https://github.com/Microsoft/vstest/pull/1745 +Get-ChildItem -Path $root -Recurse -Filter "*Tests*.csproj" | % { + $projectFilePath = $_.FullName + $projectName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath) + $reportFilePath = [IO.Path]::GetFullPath("$root/TestResults/$projectName.xml") + dotnet test $projectFilePath --logger "trx;LogFileName=$reportFilePath" + if ($LASTEXITCODE) { $exitCode = $LASTEXITCODE } +} + +Write-Host -ForegroundColor Green "All tests run." +exit $exitCode \ No newline at end of file diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index 25183af774..549b9adca0 100644 --- a/Build/build-functions.psm1 +++ b/Build/build-functions.psm1 @@ -28,7 +28,14 @@ function Update-GeneratedCode { function Start-Build([boolean] $skipUWP = $false) { write-host -foreground blue "Start-Build...`n---" - dotnet build --configuration Release "$root\UnitsNet.sln" + + $fileLoggerArg = "/logger:FileLogger,Microsoft.Build;logfile=$testReportDir\UnitsNet.msbuild.log" + + $appVeyorLoggerDll = "C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" + $appVeyorLoggerNetCoreDll = "C:\Program Files\AppVeyor\BuildAgent\dotnetcore\Appveyor.MSBuildLogger.dll" + $appVeyorLoggerArg = if (Test-Path "$appVeyorLoggerNetCoreDll") { "/logger:$appVeyorLoggerNetCoreDll" } else { "" } + + dotnet build --configuration Release "$root\UnitsNet.sln" $fileLoggerArg $appVeyorLoggerArg if ($lastexitcode -ne 0) { exit 1 } if ($skipUWP -eq $true) @@ -37,11 +44,14 @@ function Start-Build([boolean] $skipUWP = $false) { } else { + $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 + & "$msbuild" "$root\UnitsNet.WindowsRuntimeComponent.sln" /verbosity:minimal /p:Configuration=Release $fileLoggerArg $appVeyorLoggerArg if ($lastexitcode -ne 0) { exit 1 } } @@ -56,7 +66,7 @@ function Start-Tests { ) # Parent dir must exist before xunit tries to write files to it - new-item -type directory $testReportDir 1> $null + new-item -type directory -force $testReportDir 1> $null write-host -foreground blue "Run tests...`n---" foreach ($projectPath in $projectPaths) { @@ -68,7 +78,7 @@ function Start-Tests { # https://github.com/xunit/xunit/issues/1216 push-location $projectDir # -nobuild <-- this gives an error, but might want to use this to avoid extra builds - dotnet xunit -configuration Release -framework netcoreapp1.1 -xml $reportFile -nobuild + dotnet xunit -configuration Release -framework netcoreapp2.0 -xml $reportFile -nobuild if ($lastexitcode -ne 0) { exit 1 } pop-location } @@ -79,9 +89,7 @@ function Start-Tests { function Start-PackNugets { $projectPaths = @( "UnitsNet\UnitsNet.csproj", - "UnitsNet\UnitsNet.Signed.csproj", - "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj", - "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.Signed.csproj" + "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj" ) write-host -foreground blue "Pack nugets...`n---" @@ -91,7 +99,7 @@ function Start-PackNugets { } write-host -foreground yellow "WindowsRuntimeComponent project not yet supported by dotnet CLI, using nuget.exe instead" - & $nuget pack "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" -Symbols + & $nuget pack "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" write-host -foreground blue "Pack nugets...END`n" } diff --git a/Build/clean.bat b/Build/clean.bat deleted file mode 100644 index 30744fa48f..0000000000 --- a/Build/clean.bat +++ /dev/null @@ -1,4 +0,0 @@ -@echo off -SET scriptdir=%~dp0 -call powershell -NoProfile %scriptdir%\clean.ps1 -if %errorlevel% neq 0 exit /b %errorlevel% \ No newline at end of file diff --git a/Build/clean.ps1 b/Build/clean.ps1 index dd6b04a8ef..e1d6b46077 100644 --- a/Build/clean.ps1 +++ b/Build/clean.ps1 @@ -1,8 +1,27 @@ +# Don't allow using undeclared variables +Set-Strictmode -version latest + $root = "$PSScriptRoot\.." -$artifactsDir = "$root\Artifacts" -if (test-path $artifactsDir) { - write-host -foreground blue "Delete Artifacts dir" - rm -r -fo $artifactsDir -ErrorAction Continue +Write-Host -Foreground Blue "Delete dirs: bin, obj" + +[int]$deleteCount = 0 +[array]$failedToDeleteDirs = @() +Get-ChildItem $root -Include bin,obj -Recurse -Force | %{ + Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $_.FullName + if ($?) { $deleteCount++ } + else { + $failedToDeleteDirs += $_ + } } -write-host -foreground blue "Delete dirs: bin, obj" -ls $root -inc bin,obj -r -fo | ri -r -fo -ErrorAction SilentlyContinue \ No newline at end of file + +Write-Host -Foreground Green "Deleted $deleteCount folders." + +if ($failedToDeleteDirs) { + $failCount = $failedToDeleteDirs.Count + Write-Host "" + Write-Host -Foreground Red "Failed to delete $failCount dirs:" + $failedToDeleteDirs | %{ + Write-Host -Foreground Red $_.FullName + } + exit /B 1 +} \ No newline at end of file diff --git a/Build/set-version-UnitsNet.Serialization.JsonNet.ps1 b/Build/set-version-UnitsNet.Serialization.JsonNet.ps1 index 572399b01e..02628dda90 100644 --- a/Build/set-version-UnitsNet.Serialization.JsonNet.ps1 +++ b/Build/set-version-UnitsNet.Serialization.JsonNet.ps1 @@ -48,12 +48,12 @@ Import-Module "$PSScriptRoot\set-version.psm1" $root = Resolve-Path "$PSScriptRoot\.." $paramSet = $PsCmdlet.ParameterSetName -$commonPropsFile = "$root\UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.Common.props" -$versionFiles = @($commonPropsFile) +$projFile = "$root\UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj" +$versionFiles = @($projFile) $projectName = "JsonNet" # Use UnitsNet.Common.props version as base if bumping major/minor/patch -$newVersion = Get-NewProjectVersion $commonPropsFile $paramSet $setVersion $bumpVersion +$newVersion = Get-NewProjectVersion $projFile $paramSet $setVersion $bumpVersion -Set-ProjectVersion $commonPropsFile $newVersion -Invoke-CommitAndTagVersion $projectName $versionFiles $newVersion \ No newline at end of file +Set-ProjectVersion $projFile $newVersion +Invoke-CommitAndTagVersion $projectName $versionFiles $newVersion diff --git a/Build/set-version-UnitsNet.ps1 b/Build/set-version-UnitsNet.ps1 index fe378565f5..4f75f49cde 100644 --- a/Build/set-version-UnitsNet.ps1 +++ b/Build/set-version-UnitsNet.ps1 @@ -50,16 +50,16 @@ Import-Module "$PSScriptRoot\set-version.psm1" $root = Resolve-Path "$PSScriptRoot\.." $paramSet = $PsCmdlet.ParameterSetName -$commonPropsFile = "$root\UnitsNet\UnitsNet.Common.props" +$projFile = "$root\UnitsNet\UnitsNet.csproj" $winrtAssemblyInfoFile = "$root\UnitsNet\Properties\AssemblyInfo.WindowsRuntimeComponent.cs" $winrtNuspecFile = "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -$versionFiles = @($commonPropsFile, $winrtAssemblyInfoFile, $winrtNuspecFile) +$versionFiles = @($projFile, $winrtAssemblyInfoFile, $winrtNuspecFile) $projectName = "UnitsNet" # Use UnitsNet.Common.props version as base if bumping major/minor/patch -$newVersion = Get-NewProjectVersion $commonPropsFile $paramSet $setVersion $bumpVersion +$newVersion = Get-NewProjectVersion $projFile $paramSet $setVersion $bumpVersion -Set-ProjectVersion $commonPropsFile $newVersion +Set-ProjectVersion $projFile $newVersion Set-AssemblyInfoVersion $winrtAssemblyInfoFile $newVersion Set-NuspecVersion $winrtNuspecFile $newVersion Invoke-CommitAndTagVersion $projectName $versionFiles $newVersion diff --git a/Build/set-version.psm1 b/Build/set-version.psm1 index 523aa60c8f..0626a343e5 100644 --- a/Build/set-version.psm1 +++ b/Build/set-version.psm1 @@ -43,11 +43,15 @@ function Invoke-CommitAndTagVersion( } function Set-ProjectVersion([string] $file, [string] $version) { - Write-Host "$file -> $version" + $assemblyVersion = $version -replace "(\d+)(?:\.\d+)+.*", '$1.0.0.0' + Write-Host "$file -> $version (AssemblyVersion $assemblyVersion)" (Get-Content $file) -replace '.*?', "$version" | Set-Content $file + (Get-Content $file) -replace '.*?', "$assemblyVersion" | Set-Content $file } function Set-AssemblyInfoVersion([string] $file, [string] $version) { + # Strip out any suffix: "4.0.0-alpha1" => "4.0.0" + $version = $version.Split('-')[0] Write-Host "$file -> $version" (Get-Content $file) -replace 'Assembly(File)?Version\(".*?"\)', "Assembly`$1Version(`"$version`")" | Set-Content $file } @@ -107,7 +111,7 @@ function BumpSuffix([string] $oldSuffix) { # Example: # -alpha => -alpha2 # -alpha1 => -alpha2 - $match = [regex]::Match($oldSuffix, '^-(\w+)(\d+)?$'); + $match = [regex]::Match($oldSuffix, '^-([a-zA-Z]+)(\d+)?$'); $oldSuffix = $match.Groups[1].Value $numberGroup = $match.Groups[2] @@ -150,4 +154,4 @@ function Resolve-Error ($ErrorRecord=$Error[0]) } } -export-modulemember -function Get-NewProjectVersion, Set-ProjectVersion, Set-AssemblyInfoVersion, Invoke-CommitAndTagVersion, Set-NuspecVersion \ No newline at end of file +export-modulemember -function Get-NewProjectVersion, Set-ProjectVersion, Set-AssemblyInfoVersion, Invoke-CommitAndTagVersion, Set-NuspecVersion diff --git a/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs b/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs deleted file mode 100644 index 57f6cdbb3e..0000000000 --- a/Common/GeneratedCode/Quantities/Acceleration.Common.g.cs +++ /dev/null @@ -1,742 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Acceleration : IQuantity -#else - public partial struct Acceleration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AccelerationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Acceleration() - { - BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit MeterPerSecondSquared. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Acceleration(double meterspersecondsquared) - { - _value = Convert.ToDouble(meterspersecondsquared); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Acceleration(double numericValue, AccelerationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit MeterPerSecondSquared. - /// - /// Value assuming base unit MeterPerSecondSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Acceleration(long meterspersecondsquared) : this(Convert.ToDouble(meterspersecondsquared), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit MeterPerSecondSquared. - /// - /// Value assuming base unit MeterPerSecondSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Acceleration(decimal meterspersecondsquared) : this(Convert.ToDouble(meterspersecondsquared), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Acceleration; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Acceleration quantity. - /// - public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); - - /// - /// Get Acceleration in CentimetersPerSecondSquared. - /// - public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); - - /// - /// Get Acceleration in DecimetersPerSecondSquared. - /// - public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); - - /// - /// Get Acceleration in FeetPerSecondSquared. - /// - public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); - - /// - /// Get Acceleration in InchesPerSecondSquared. - /// - public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); - - /// - /// Get Acceleration in KilometersPerSecondSquared. - /// - public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); - - /// - /// Get Acceleration in KnotsPerHour. - /// - public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); - - /// - /// Get Acceleration in KnotsPerMinute. - /// - public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); - - /// - /// Get Acceleration in KnotsPerSecond. - /// - public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); - - /// - /// Get Acceleration in MetersPerSecondSquared. - /// - public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); - - /// - /// Get Acceleration in MicrometersPerSecondSquared. - /// - public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); - - /// - /// Get Acceleration in MillimetersPerSecondSquared. - /// - public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); - - /// - /// Get Acceleration in NanometersPerSecondSquared. - /// - public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); - - /// - /// Get Acceleration in StandardGravity. - /// - public double StandardGravity => As(AccelerationUnit.StandardGravity); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. - /// - public static Acceleration Zero => new Acceleration(0, BaseUnit); - - /// - /// Get Acceleration from CentimetersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromCentimetersPerSecondSquared(double centimeterspersecondsquared) -#else - public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) -#endif - { - double value = (double) centimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); - } - - /// - /// Get Acceleration from DecimetersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromDecimetersPerSecondSquared(double decimeterspersecondsquared) -#else - public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) -#endif - { - double value = (double) decimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); - } - - /// - /// Get Acceleration from FeetPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) -#else - public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) -#endif - { - double value = (double) feetpersecondsquared; - return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); - } - - /// - /// Get Acceleration from InchesPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) -#else - public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) -#endif - { - double value = (double) inchespersecondsquared; - return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); - } - - /// - /// Get Acceleration from KilometersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKilometersPerSecondSquared(double kilometerspersecondsquared) -#else - public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) -#endif - { - double value = (double) kilometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); - } - - /// - /// Get Acceleration from KnotsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerHour(double knotsperhour) -#else - public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) -#endif - { - double value = (double) knotsperhour; - return new Acceleration(value, AccelerationUnit.KnotPerHour); - } - - /// - /// Get Acceleration from KnotsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerMinute(double knotsperminute) -#else - public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) -#endif - { - double value = (double) knotsperminute; - return new Acceleration(value, AccelerationUnit.KnotPerMinute); - } - - /// - /// Get Acceleration from KnotsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerSecond(double knotspersecond) -#else - public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) -#endif - { - double value = (double) knotspersecond; - return new Acceleration(value, AccelerationUnit.KnotPerSecond); - } - - /// - /// Get Acceleration from MetersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMetersPerSecondSquared(double meterspersecondsquared) -#else - public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) -#endif - { - double value = (double) meterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); - } - - /// - /// Get Acceleration from MicrometersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMicrometersPerSecondSquared(double micrometerspersecondsquared) -#else - public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) -#endif - { - double value = (double) micrometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); - } - - /// - /// Get Acceleration from MillimetersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMillimetersPerSecondSquared(double millimeterspersecondsquared) -#else - public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) -#endif - { - double value = (double) millimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); - } - - /// - /// Get Acceleration from NanometersPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromNanometersPerSecondSquared(double nanometerspersecondsquared) -#else - public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) -#endif - { - double value = (double) nanometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); - } - - /// - /// Get Acceleration from StandardGravity. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromStandardGravity(double standardgravity) -#else - public static Acceleration FromStandardGravity(QuantityValue standardgravity) -#endif - { - double value = (double) standardgravity; - return new Acceleration(value, AccelerationUnit.StandardGravity); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Acceleration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Acceleration From(double value, AccelerationUnit fromUnit) -#else - public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) -#endif - { - return new Acceleration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Acceleration)) throw new ArgumentException("Expected type Acceleration.", nameof(obj)); - - return CompareTo((Acceleration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Acceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Acceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Acceleration)) - return false; - - var objQuantity = (Acceleration)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Acceleration by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Acceleration, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Acceleration other, Acceleration maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Acceleration. - public override int GetHashCode() - { - return new { type = typeof(Acceleration), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AccelerationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Acceleration to another Acceleration with the unit representation . - /// - /// A Acceleration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Acceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; - case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; - case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; - case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; - case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return _value; - case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; - case AccelerationUnit.StandardGravity: return _value*9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AccelerationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; - case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; - case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; - case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; - case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; - case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; - case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Acceleration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Acceleration result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AccelerationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is MeterPerSecondSquared - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AccelerationUnit ToStringDefaultUnit { get; set; } = AccelerationUnit.MeterPerSecondSquared; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AccelerationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Acceleration - /// - public static Acceleration MaxValue => new Acceleration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Acceleration - /// - public static Acceleration MinValue => new Acceleration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Acceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Acceleration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs b/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs deleted file mode 100644 index e1f8b61fca..0000000000 --- a/Common/GeneratedCode/Quantities/AmountOfSubstance.Common.g.cs +++ /dev/null @@ -1,784 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AmountOfSubstance : IQuantity -#else - public partial struct AmountOfSubstance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmountOfSubstanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AmountOfSubstance() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Mole. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public AmountOfSubstance(double moles) - { - _value = Convert.ToDouble(moles); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - AmountOfSubstance(double numericValue, AmountOfSubstanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Mole. - /// - /// Value assuming base unit Mole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AmountOfSubstance(long moles) : this(Convert.ToDouble(moles), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Mole. - /// - /// Value assuming base unit Mole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AmountOfSubstance(decimal moles) : this(Convert.ToDouble(moles), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AmountOfSubstance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AmountOfSubstance quantity. - /// - public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); - - /// - /// Get AmountOfSubstance in Centimoles. - /// - public double Centimoles => As(AmountOfSubstanceUnit.Centimole); - - /// - /// Get AmountOfSubstance in CentipoundMoles. - /// - public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); - - /// - /// Get AmountOfSubstance in Decimoles. - /// - public double Decimoles => As(AmountOfSubstanceUnit.Decimole); - - /// - /// Get AmountOfSubstance in DecipoundMoles. - /// - public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); - - /// - /// Get AmountOfSubstance in Kilomoles. - /// - public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); - - /// - /// Get AmountOfSubstance in KilopoundMoles. - /// - public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); - - /// - /// Get AmountOfSubstance in Megamoles. - /// - public double Megamoles => As(AmountOfSubstanceUnit.Megamole); - - /// - /// Get AmountOfSubstance in Micromoles. - /// - public double Micromoles => As(AmountOfSubstanceUnit.Micromole); - - /// - /// Get AmountOfSubstance in MicropoundMoles. - /// - public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); - - /// - /// Get AmountOfSubstance in Millimoles. - /// - public double Millimoles => As(AmountOfSubstanceUnit.Millimole); - - /// - /// Get AmountOfSubstance in MillipoundMoles. - /// - public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); - - /// - /// Get AmountOfSubstance in Moles. - /// - public double Moles => As(AmountOfSubstanceUnit.Mole); - - /// - /// Get AmountOfSubstance in Nanomoles. - /// - public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); - - /// - /// Get AmountOfSubstance in NanopoundMoles. - /// - public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); - - /// - /// Get AmountOfSubstance in PoundMoles. - /// - public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Mole. - /// - public static AmountOfSubstance Zero => new AmountOfSubstance(0, BaseUnit); - - /// - /// Get AmountOfSubstance from Centimoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentimoles(double centimoles) -#else - public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) -#endif - { - double value = (double) centimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); - } - - /// - /// Get AmountOfSubstance from CentipoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) -#else - public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) -#endif - { - double value = (double) centipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); - } - - /// - /// Get AmountOfSubstance from Decimoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecimoles(double decimoles) -#else - public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) -#endif - { - double value = (double) decimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); - } - - /// - /// Get AmountOfSubstance from DecipoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) -#else - public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) -#endif - { - double value = (double) decipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); - } - - /// - /// Get AmountOfSubstance from Kilomoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilomoles(double kilomoles) -#else - public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) -#endif - { - double value = (double) kilomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); - } - - /// - /// Get AmountOfSubstance from KilopoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) -#else - public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) -#endif - { - double value = (double) kilopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); - } - - /// - /// Get AmountOfSubstance from Megamoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMegamoles(double megamoles) -#else - public static AmountOfSubstance FromMegamoles(QuantityValue megamoles) -#endif - { - double value = (double) megamoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); - } - - /// - /// Get AmountOfSubstance from Micromoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicromoles(double micromoles) -#else - public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) -#endif - { - double value = (double) micromoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); - } - - /// - /// Get AmountOfSubstance from MicropoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) -#else - public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) -#endif - { - double value = (double) micropoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); - } - - /// - /// Get AmountOfSubstance from Millimoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillimoles(double millimoles) -#else - public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) -#endif - { - double value = (double) millimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); - } - - /// - /// Get AmountOfSubstance from MillipoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) -#else - public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) -#endif - { - double value = (double) millipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); - } - - /// - /// Get AmountOfSubstance from Moles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMoles(double moles) -#else - public static AmountOfSubstance FromMoles(QuantityValue moles) -#endif - { - double value = (double) moles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); - } - - /// - /// Get AmountOfSubstance from Nanomoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanomoles(double nanomoles) -#else - public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) -#endif - { - double value = (double) nanomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); - } - - /// - /// Get AmountOfSubstance from NanopoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) -#else - public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) -#endif - { - double value = (double) nanopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); - } - - /// - /// Get AmountOfSubstance from PoundMoles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromPoundMoles(double poundmoles) -#else - public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) -#endif - { - double value = (double) poundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmountOfSubstance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUnit) -#else - public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) -#endif - { - return new AmountOfSubstance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmountOfSubstanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AmountOfSubstance)) throw new ArgumentException("Expected type AmountOfSubstance.", nameof(obj)); - - return CompareTo((AmountOfSubstance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AmountOfSubstance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmountOfSubstance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is AmountOfSubstance)) - return false; - - var objQuantity = (AmountOfSubstance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another AmountOfSubstance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(AmountOfSubstance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(AmountOfSubstance other, AmountOfSubstance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmountOfSubstance. - public override int GetHashCode() - { - return new { type = typeof(AmountOfSubstance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . - /// - /// A AmountOfSubstance with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmountOfSubstance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AmountOfSubstanceUnit.Centimole: return (_value) * 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (_value*453.59237) * 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (_value) * 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (_value*453.59237) * 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (_value) * 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (_value*453.59237) * 1e3d; - case AmountOfSubstanceUnit.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 Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmountOfSubstance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmountOfSubstanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Mole - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AmountOfSubstanceUnit ToStringDefaultUnit { get; set; } = AmountOfSubstanceUnit.Mole; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AmountOfSubstanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MaxValue => new AmountOfSubstance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MinValue => new AmountOfSubstance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AmountOfSubstance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs b/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs deleted file mode 100644 index f54d41b524..0000000000 --- a/Common/GeneratedCode/Quantities/AmplitudeRatio.Common.g.cs +++ /dev/null @@ -1,552 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AmplitudeRatio : IQuantity -#else - public partial struct AmplitudeRatio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmplitudeRatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AmplitudeRatio() - { - } - - /// - /// Creates the quantity with the given value in the base unit DecibelVolt. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public AmplitudeRatio(double decibelvolts) - { - _value = Convert.ToDouble(decibelvolts); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - AmplitudeRatio(double numericValue, AmplitudeRatioUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit DecibelVolt. - /// - /// Value assuming base unit DecibelVolt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AmplitudeRatio(long decibelvolts) : this(Convert.ToDouble(decibelvolts), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit DecibelVolt. - /// - /// Value assuming base unit DecibelVolt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AmplitudeRatio(decimal decibelvolts) : this(Convert.ToDouble(decibelvolts), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AmplitudeRatio; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AmplitudeRatio quantity. - /// - public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); - - /// - /// Get AmplitudeRatio in DecibelMicrovolts. - /// - public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); - - /// - /// Get AmplitudeRatio in DecibelMillivolts. - /// - public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); - - /// - /// Get AmplitudeRatio in DecibelsUnloaded. - /// - public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); - - /// - /// Get AmplitudeRatio in DecibelVolts. - /// - public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. - /// - public static AmplitudeRatio Zero => new AmplitudeRatio(0, BaseUnit); - - /// - /// Get AmplitudeRatio from DecibelMicrovolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) -#else - public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) -#endif - { - double value = (double) decibelmicrovolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); - } - - /// - /// Get AmplitudeRatio from DecibelMillivolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) -#else - public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) -#endif - { - double value = (double) decibelmillivolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); - } - - /// - /// Get AmplitudeRatio from DecibelsUnloaded. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) -#else - public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) -#endif - { - double value = (double) decibelsunloaded; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); - } - - /// - /// Get AmplitudeRatio from DecibelVolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelVolts(double decibelvolts) -#else - public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) -#endif - { - double value = (double) decibelvolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmplitudeRatio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) -#else - public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) -#endif - { - return new AmplitudeRatio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmplitudeRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AmplitudeRatio)) throw new ArgumentException("Expected type AmplitudeRatio.", nameof(obj)); - - return CompareTo((AmplitudeRatio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AmplitudeRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmplitudeRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is AmplitudeRatio)) - return false; - - var objQuantity = (AmplitudeRatio)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another AmplitudeRatio by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(AmplitudeRatio, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(AmplitudeRatio other, AmplitudeRatio maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmplitudeRatio. - public override int GetHashCode() - { - return new { type = typeof(AmplitudeRatio), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . - /// - /// A AmplitudeRatio with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmplitudeRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return _value - 120; - case AmplitudeRatioUnit.DecibelMillivolt: return _value - 60; - case AmplitudeRatioUnit.DecibelUnloaded: return _value - 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AmplitudeRatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return baseUnitValue + 120; - case AmplitudeRatioUnit.DecibelMillivolt: return baseUnitValue + 60; - case AmplitudeRatioUnit.DecibelUnloaded: return baseUnitValue + 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmplitudeRatio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmplitudeRatioUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is DecibelVolt - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AmplitudeRatioUnit ToStringDefaultUnit { get; set; } = AmplitudeRatioUnit.DecibelVolt; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AmplitudeRatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MaxValue => new AmplitudeRatio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MinValue => new AmplitudeRatio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AmplitudeRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Angle.Common.g.cs b/Common/GeneratedCode/Quantities/Angle.Common.g.cs deleted file mode 100644 index b46e515994..0000000000 --- a/Common/GeneratedCode/Quantities/Angle.Common.g.cs +++ /dev/null @@ -1,762 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Angle : IQuantity -#else - public partial struct Angle : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AngleUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Angle() - { - } - - /// - /// Creates the quantity with the given value in the base unit Degree. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Angle(double degrees) - { - _value = Convert.ToDouble(degrees); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Angle(double numericValue, AngleUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Degree. - /// - /// Value assuming base unit Degree. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Angle(long degrees) : this(Convert.ToDouble(degrees), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Degree. - /// - /// Value assuming base unit Degree. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Angle(decimal degrees) : this(Convert.ToDouble(degrees), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Angle; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AngleUnit BaseUnit => AngleUnit.Degree; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Angle quantity. - /// - public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); - - /// - /// Get Angle in Arcminutes. - /// - public double Arcminutes => As(AngleUnit.Arcminute); - - /// - /// Get Angle in Arcseconds. - /// - public double Arcseconds => As(AngleUnit.Arcsecond); - - /// - /// Get Angle in Centiradians. - /// - public double Centiradians => As(AngleUnit.Centiradian); - - /// - /// Get Angle in Deciradians. - /// - public double Deciradians => As(AngleUnit.Deciradian); - - /// - /// Get Angle in Degrees. - /// - public double Degrees => As(AngleUnit.Degree); - - /// - /// Get Angle in Gradians. - /// - public double Gradians => As(AngleUnit.Gradian); - - /// - /// Get Angle in Microdegrees. - /// - public double Microdegrees => As(AngleUnit.Microdegree); - - /// - /// Get Angle in Microradians. - /// - public double Microradians => As(AngleUnit.Microradian); - - /// - /// Get Angle in Millidegrees. - /// - public double Millidegrees => As(AngleUnit.Millidegree); - - /// - /// Get Angle in Milliradians. - /// - public double Milliradians => As(AngleUnit.Milliradian); - - /// - /// Get Angle in Nanodegrees. - /// - public double Nanodegrees => As(AngleUnit.Nanodegree); - - /// - /// Get Angle in Nanoradians. - /// - public double Nanoradians => As(AngleUnit.Nanoradian); - - /// - /// Get Angle in Radians. - /// - public double Radians => As(AngleUnit.Radian); - - /// - /// Get Angle in Revolutions. - /// - public double Revolutions => As(AngleUnit.Revolution); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Degree. - /// - public static Angle Zero => new Angle(0, BaseUnit); - - /// - /// Get Angle from Arcminutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcminutes(double arcminutes) -#else - public static Angle FromArcminutes(QuantityValue arcminutes) -#endif - { - double value = (double) arcminutes; - return new Angle(value, AngleUnit.Arcminute); - } - - /// - /// Get Angle from Arcseconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcseconds(double arcseconds) -#else - public static Angle FromArcseconds(QuantityValue arcseconds) -#endif - { - double value = (double) arcseconds; - return new Angle(value, AngleUnit.Arcsecond); - } - - /// - /// Get Angle from Centiradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromCentiradians(double centiradians) -#else - public static Angle FromCentiradians(QuantityValue centiradians) -#endif - { - double value = (double) centiradians; - return new Angle(value, AngleUnit.Centiradian); - } - - /// - /// Get Angle from Deciradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDeciradians(double deciradians) -#else - public static Angle FromDeciradians(QuantityValue deciradians) -#endif - { - double value = (double) deciradians; - return new Angle(value, AngleUnit.Deciradian); - } - - /// - /// Get Angle from Degrees. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDegrees(double degrees) -#else - public static Angle FromDegrees(QuantityValue degrees) -#endif - { - double value = (double) degrees; - return new Angle(value, AngleUnit.Degree); - } - - /// - /// Get Angle from Gradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromGradians(double gradians) -#else - public static Angle FromGradians(QuantityValue gradians) -#endif - { - double value = (double) gradians; - return new Angle(value, AngleUnit.Gradian); - } - - /// - /// Get Angle from Microdegrees. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicrodegrees(double microdegrees) -#else - public static Angle FromMicrodegrees(QuantityValue microdegrees) -#endif - { - double value = (double) microdegrees; - return new Angle(value, AngleUnit.Microdegree); - } - - /// - /// Get Angle from Microradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicroradians(double microradians) -#else - public static Angle FromMicroradians(QuantityValue microradians) -#endif - { - double value = (double) microradians; - return new Angle(value, AngleUnit.Microradian); - } - - /// - /// Get Angle from Millidegrees. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMillidegrees(double millidegrees) -#else - public static Angle FromMillidegrees(QuantityValue millidegrees) -#endif - { - double value = (double) millidegrees; - return new Angle(value, AngleUnit.Millidegree); - } - - /// - /// Get Angle from Milliradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMilliradians(double milliradians) -#else - public static Angle FromMilliradians(QuantityValue milliradians) -#endif - { - double value = (double) milliradians; - return new Angle(value, AngleUnit.Milliradian); - } - - /// - /// Get Angle from Nanodegrees. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanodegrees(double nanodegrees) -#else - public static Angle FromNanodegrees(QuantityValue nanodegrees) -#endif - { - double value = (double) nanodegrees; - return new Angle(value, AngleUnit.Nanodegree); - } - - /// - /// Get Angle from Nanoradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanoradians(double nanoradians) -#else - public static Angle FromNanoradians(QuantityValue nanoradians) -#endif - { - double value = (double) nanoradians; - return new Angle(value, AngleUnit.Nanoradian); - } - - /// - /// Get Angle from Radians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRadians(double radians) -#else - public static Angle FromRadians(QuantityValue radians) -#endif - { - double value = (double) radians; - return new Angle(value, AngleUnit.Radian); - } - - /// - /// Get Angle from Revolutions. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRevolutions(double revolutions) -#else - public static Angle FromRevolutions(QuantityValue revolutions) -#endif - { - double value = (double) revolutions; - return new Angle(value, AngleUnit.Revolution); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Angle unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Angle From(double value, AngleUnit fromUnit) -#else - public static Angle From(QuantityValue value, AngleUnit fromUnit) -#endif - { - return new Angle((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Angle)) throw new ArgumentException("Expected type Angle.", nameof(obj)); - - return CompareTo((Angle)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Angle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Angle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Angle)) - return false; - - var objQuantity = (Angle)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Angle by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Angle, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Angle other, Angle maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Angle. - public override int GetHashCode() - { - return new { type = typeof(Angle), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AngleUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Angle to another Angle with the unit representation . - /// - /// A Angle with the specified unit. - public Angle ToUnit(AngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Angle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AngleUnit.Arcminute: return _value/60; - case AngleUnit.Arcsecond: return _value/3600; - case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; - case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; - case AngleUnit.Degree: return _value; - case AngleUnit.Gradian: return _value*0.9; - case AngleUnit.Microdegree: return (_value) * 1e-6d; - case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; - case AngleUnit.Millidegree: return (_value) * 1e-3d; - case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; - case AngleUnit.Nanodegree: return (_value) * 1e-9d; - case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; - case AngleUnit.Radian: return _value*180/Math.PI; - case AngleUnit.Revolution: return _value*360; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AngleUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AngleUnit.Arcminute: return baseUnitValue*60; - case AngleUnit.Arcsecond: return baseUnitValue*3600; - case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; - case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; - case AngleUnit.Degree: return baseUnitValue; - case AngleUnit.Gradian: return baseUnitValue/0.9; - case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; - case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; - case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; - case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; - case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; - case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; - case AngleUnit.Radian: return baseUnitValue/180*Math.PI; - case AngleUnit.Revolution: return baseUnitValue/360; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Angle Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Angle result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AngleUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Degree - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AngleUnit ToStringDefaultUnit { get; set; } = AngleUnit.Degree; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AngleUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Angle - /// - public static Angle MaxValue => new Angle(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Angle - /// - public static Angle MinValue => new Angle(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Angle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Angle.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs deleted file mode 100644 index 9e23d63165..0000000000 --- a/Common/GeneratedCode/Quantities/ApparentEnergy.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ApparentEnergy : IQuantity -#else - public partial struct ApparentEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ApparentEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit VoltampereHour. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ApparentEnergy(double voltamperehours) - { - _value = Convert.ToDouble(voltamperehours); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ApparentEnergy(double numericValue, ApparentEnergyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltampereHour. - /// - /// Value assuming base unit VoltampereHour. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ApparentEnergy(long voltamperehours) : this(Convert.ToDouble(voltamperehours), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltampereHour. - /// - /// Value assuming base unit VoltampereHour. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ApparentEnergy(decimal voltamperehours) : this(Convert.ToDouble(voltamperehours), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ApparentEnergy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ApparentEnergy quantity. - /// - public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); - - /// - /// Get ApparentEnergy in KilovoltampereHours. - /// - public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); - - /// - /// Get ApparentEnergy in MegavoltampereHours. - /// - public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); - - /// - /// Get ApparentEnergy in VoltampereHours. - /// - public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. - /// - public static ApparentEnergy Zero => new ApparentEnergy(0, BaseUnit); - - /// - /// Get ApparentEnergy from KilovoltampereHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) -#else - public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) -#endif - { - double value = (double) kilovoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); - } - - /// - /// Get ApparentEnergy from MegavoltampereHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) -#else - public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) -#endif - { - double value = (double) megavoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); - } - - /// - /// Get ApparentEnergy from VoltampereHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromVoltampereHours(double voltamperehours) -#else - public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) -#endif - { - double value = (double) voltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) -#else - public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) -#endif - { - return new ApparentEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ApparentEnergy)) throw new ArgumentException("Expected type ApparentEnergy.", nameof(obj)); - - return CompareTo((ApparentEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ApparentEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ApparentEnergy)) - return false; - - var objQuantity = (ApparentEnergy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ApparentEnergy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ApparentEnergy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ApparentEnergy other, ApparentEnergy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentEnergy. - public override int GetHashCode() - { - return new { type = typeof(ApparentEnergy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . - /// - /// A ApparentEnergy with the specified unit. - public ApparentEnergy ToUnit(ApparentEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (_value) * 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (_value) * 1e6d; - case ApparentEnergyUnit.VoltampereHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (baseUnitValue) / 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (baseUnitValue) / 1e6d; - case ApparentEnergyUnit.VoltampereHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltampereHour - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ApparentEnergyUnit ToStringDefaultUnit { get; set; } = ApparentEnergyUnit.VoltampereHour; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ApparentEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ApparentEnergy - /// - public static ApparentEnergy MaxValue => new ApparentEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ApparentEnergy - /// - public static ApparentEnergy MinValue => new ApparentEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ApparentEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs b/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs deleted file mode 100644 index bd44ccbe19..0000000000 --- a/Common/GeneratedCode/Quantities/ApparentPower.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ApparentPower : IQuantity -#else - public partial struct ApparentPower : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentPowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ApparentPower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Voltampere. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ApparentPower(double voltamperes) - { - _value = Convert.ToDouble(voltamperes); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ApparentPower(double numericValue, ApparentPowerUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Voltampere. - /// - /// Value assuming base unit Voltampere. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ApparentPower(long voltamperes) : this(Convert.ToDouble(voltamperes), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Voltampere. - /// - /// Value assuming base unit Voltampere. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ApparentPower(decimal voltamperes) : this(Convert.ToDouble(voltamperes), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ApparentPower; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ApparentPower quantity. - /// - public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); - - /// - /// Get ApparentPower in Gigavoltamperes. - /// - public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); - - /// - /// Get ApparentPower in Kilovoltamperes. - /// - public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); - - /// - /// Get ApparentPower in Megavoltamperes. - /// - public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); - - /// - /// Get ApparentPower in Voltamperes. - /// - public double Voltamperes => As(ApparentPowerUnit.Voltampere); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. - /// - public static ApparentPower Zero => new ApparentPower(0, BaseUnit); - - /// - /// Get ApparentPower from Gigavoltamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromGigavoltamperes(double gigavoltamperes) -#else - public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) -#endif - { - double value = (double) gigavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); - } - - /// - /// Get ApparentPower from Kilovoltamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromKilovoltamperes(double kilovoltamperes) -#else - public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) -#endif - { - double value = (double) kilovoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); - } - - /// - /// Get ApparentPower from Megavoltamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromMegavoltamperes(double megavoltamperes) -#else - public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) -#endif - { - double value = (double) megavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); - } - - /// - /// Get ApparentPower from Voltamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromVoltamperes(double voltamperes) -#else - public static ApparentPower FromVoltamperes(QuantityValue voltamperes) -#endif - { - double value = (double) voltamperes; - return new ApparentPower(value, ApparentPowerUnit.Voltampere); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentPower unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentPower From(double value, ApparentPowerUnit fromUnit) -#else - public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) -#endif - { - return new ApparentPower((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentPowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ApparentPower)) throw new ArgumentException("Expected type ApparentPower.", nameof(obj)); - - return CompareTo((ApparentPower)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ApparentPower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentPower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ApparentPower)) - return false; - - var objQuantity = (ApparentPower)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ApparentPower by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ApparentPower, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ApparentPower other, ApparentPower maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentPower. - public override int GetHashCode() - { - return new { type = typeof(ApparentPower), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentPowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentPower to another ApparentPower with the unit representation . - /// - /// A ApparentPower with the specified unit. - public ApparentPower ToUnit(ApparentPowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentPower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ApparentPowerUnit.Gigavoltampere: return (_value) * 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (_value) * 1e3d; - case ApparentPowerUnit.Megavoltampere: return (_value) * 1e6d; - case ApparentPowerUnit.Voltampere: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentPowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentPowerUnit.Gigavoltampere: return (baseUnitValue) / 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (baseUnitValue) / 1e3d; - case ApparentPowerUnit.Megavoltampere: return (baseUnitValue) / 1e6d; - case ApparentPowerUnit.Voltampere: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentPower Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentPower result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentPowerUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Voltampere - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ApparentPowerUnit ToStringDefaultUnit { get; set; } = ApparentPowerUnit.Voltampere; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ApparentPowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ApparentPower - /// - public static ApparentPower MaxValue => new ApparentPower(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ApparentPower - /// - public static ApparentPower MinValue => new ApparentPower(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ApparentPower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentPower.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Area.Common.g.cs b/Common/GeneratedCode/Quantities/Area.Common.g.cs deleted file mode 100644 index 1d662ccf7a..0000000000 --- a/Common/GeneratedCode/Quantities/Area.Common.g.cs +++ /dev/null @@ -1,742 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Area : IQuantity -#else - public partial struct Area : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Area() - { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit SquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Area(double squaremeters) - { - _value = Convert.ToDouble(squaremeters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Area(double numericValue, AreaUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit SquareMeter. - /// - /// Value assuming base unit SquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Area(long squaremeters) : this(Convert.ToDouble(squaremeters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit SquareMeter. - /// - /// Value assuming base unit SquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Area(decimal squaremeters) : this(Convert.ToDouble(squaremeters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Area; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AreaUnit BaseUnit => AreaUnit.SquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Area quantity. - /// - public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); - - /// - /// Get Area in Acres. - /// - public double Acres => As(AreaUnit.Acre); - - /// - /// Get Area in Hectares. - /// - public double Hectares => As(AreaUnit.Hectare); - - /// - /// Get Area in SquareCentimeters. - /// - public double SquareCentimeters => As(AreaUnit.SquareCentimeter); - - /// - /// Get Area in SquareDecimeters. - /// - public double SquareDecimeters => As(AreaUnit.SquareDecimeter); - - /// - /// Get Area in SquareFeet. - /// - public double SquareFeet => As(AreaUnit.SquareFoot); - - /// - /// Get Area in SquareInches. - /// - public double SquareInches => As(AreaUnit.SquareInch); - - /// - /// Get Area in SquareKilometers. - /// - public double SquareKilometers => As(AreaUnit.SquareKilometer); - - /// - /// Get Area in SquareMeters. - /// - public double SquareMeters => As(AreaUnit.SquareMeter); - - /// - /// Get Area in SquareMicrometers. - /// - public double SquareMicrometers => As(AreaUnit.SquareMicrometer); - - /// - /// Get Area in SquareMiles. - /// - public double SquareMiles => As(AreaUnit.SquareMile); - - /// - /// Get Area in SquareMillimeters. - /// - public double SquareMillimeters => As(AreaUnit.SquareMillimeter); - - /// - /// Get Area in SquareYards. - /// - public double SquareYards => As(AreaUnit.SquareYard); - - /// - /// Get Area in UsSurveySquareFeet. - /// - public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. - /// - public static Area Zero => new Area(0, BaseUnit); - - /// - /// Get Area from Acres. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromAcres(double acres) -#else - public static Area FromAcres(QuantityValue acres) -#endif - { - double value = (double) acres; - return new Area(value, AreaUnit.Acre); - } - - /// - /// Get Area from Hectares. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromHectares(double hectares) -#else - public static Area FromHectares(QuantityValue hectares) -#endif - { - double value = (double) hectares; - return new Area(value, AreaUnit.Hectare); - } - - /// - /// Get Area from SquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareCentimeters(double squarecentimeters) -#else - public static Area FromSquareCentimeters(QuantityValue squarecentimeters) -#endif - { - double value = (double) squarecentimeters; - return new Area(value, AreaUnit.SquareCentimeter); - } - - /// - /// Get Area from SquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareDecimeters(double squaredecimeters) -#else - public static Area FromSquareDecimeters(QuantityValue squaredecimeters) -#endif - { - double value = (double) squaredecimeters; - return new Area(value, AreaUnit.SquareDecimeter); - } - - /// - /// Get Area from SquareFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareFeet(double squarefeet) -#else - public static Area FromSquareFeet(QuantityValue squarefeet) -#endif - { - double value = (double) squarefeet; - return new Area(value, AreaUnit.SquareFoot); - } - - /// - /// Get Area from SquareInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareInches(double squareinches) -#else - public static Area FromSquareInches(QuantityValue squareinches) -#endif - { - double value = (double) squareinches; - return new Area(value, AreaUnit.SquareInch); - } - - /// - /// Get Area from SquareKilometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareKilometers(double squarekilometers) -#else - public static Area FromSquareKilometers(QuantityValue squarekilometers) -#endif - { - double value = (double) squarekilometers; - return new Area(value, AreaUnit.SquareKilometer); - } - - /// - /// Get Area from SquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMeters(double squaremeters) -#else - public static Area FromSquareMeters(QuantityValue squaremeters) -#endif - { - double value = (double) squaremeters; - return new Area(value, AreaUnit.SquareMeter); - } - - /// - /// Get Area from SquareMicrometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMicrometers(double squaremicrometers) -#else - public static Area FromSquareMicrometers(QuantityValue squaremicrometers) -#endif - { - double value = (double) squaremicrometers; - return new Area(value, AreaUnit.SquareMicrometer); - } - - /// - /// Get Area from SquareMiles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMiles(double squaremiles) -#else - public static Area FromSquareMiles(QuantityValue squaremiles) -#endif - { - double value = (double) squaremiles; - return new Area(value, AreaUnit.SquareMile); - } - - /// - /// Get Area from SquareMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMillimeters(double squaremillimeters) -#else - public static Area FromSquareMillimeters(QuantityValue squaremillimeters) -#endif - { - double value = (double) squaremillimeters; - return new Area(value, AreaUnit.SquareMillimeter); - } - - /// - /// Get Area from SquareYards. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareYards(double squareyards) -#else - public static Area FromSquareYards(QuantityValue squareyards) -#endif - { - double value = (double) squareyards; - return new Area(value, AreaUnit.SquareYard); - } - - /// - /// Get Area from UsSurveySquareFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) -#else - public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) -#endif - { - double value = (double) ussurveysquarefeet; - return new Area(value, AreaUnit.UsSurveySquareFoot); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Area unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Area From(double value, AreaUnit fromUnit) -#else - public static Area From(QuantityValue value, AreaUnit fromUnit) -#endif - { - return new Area((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Area)) throw new ArgumentException("Expected type Area.", nameof(obj)); - - return CompareTo((Area)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Area other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Area, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Area)) - return false; - - var objQuantity = (Area)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Area by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Area, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Area other, Area maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Area. - public override int GetHashCode() - { - return new { type = typeof(Area), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Area to another Area with the unit representation . - /// - /// A Area with the specified unit. - public Area ToUnit(AreaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Area(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaUnit.Acre: return _value*4046.85642; - case AreaUnit.Hectare: return _value*1e4; - case AreaUnit.SquareCentimeter: return _value*1e-4; - case AreaUnit.SquareDecimeter: return _value*1e-2; - case AreaUnit.SquareFoot: return _value*0.092903; - case AreaUnit.SquareInch: return _value*0.00064516; - case AreaUnit.SquareKilometer: return _value*1e6; - case AreaUnit.SquareMeter: return _value; - case AreaUnit.SquareMicrometer: return _value*1e-12; - case AreaUnit.SquareMile: return _value*2.59e6; - case AreaUnit.SquareMillimeter: return _value*1e-6; - case AreaUnit.SquareYard: return _value*0.836127; - case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaUnit.Acre: return baseUnitValue/4046.85642; - case AreaUnit.Hectare: return baseUnitValue/1e4; - case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; - case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; - case AreaUnit.SquareFoot: return baseUnitValue/0.092903; - case AreaUnit.SquareInch: return baseUnitValue/0.00064516; - case AreaUnit.SquareKilometer: return baseUnitValue/1e6; - case AreaUnit.SquareMeter: return baseUnitValue; - case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; - case AreaUnit.SquareMile: return baseUnitValue/2.59e6; - case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; - case AreaUnit.SquareYard: return baseUnitValue/0.836127; - case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Area Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Area result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is SquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AreaUnit ToStringDefaultUnit { get; set; } = AreaUnit.SquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Area - /// - public static Area MaxValue => new Area(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Area - /// - public static Area MinValue => new Area(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Area.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Area.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs b/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs deleted file mode 100644 index 87f755b0b6..0000000000 --- a/Common/GeneratedCode/Quantities/AreaDensity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The area density of a two-dimensional object is calculated as the mass per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AreaDensity : IQuantity -#else - public partial struct AreaDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AreaDensity() - { - BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public AreaDensity(double kilogramspersquaremeter) - { - _value = Convert.ToDouble(kilogramspersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - AreaDensity(double numericValue, AreaDensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerSquareMeter. - /// - /// Value assuming base unit KilogramPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AreaDensity(long kilogramspersquaremeter) : this(Convert.ToDouble(kilogramspersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerSquareMeter. - /// - /// Value assuming base unit KilogramPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AreaDensity(decimal kilogramspersquaremeter) : this(Convert.ToDouble(kilogramspersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AreaDensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AreaDensity quantity. - /// - public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); - - /// - /// Get AreaDensity in KilogramsPerSquareMeter. - /// - public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. - /// - public static AreaDensity Zero => new AreaDensity(0, BaseUnit); - - /// - /// Get AreaDensity from KilogramsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) -#else - public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) -#endif - { - double value = (double) kilogramspersquaremeter; - return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaDensity From(double value, AreaDensityUnit fromUnit) -#else - public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) -#endif - { - return new AreaDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AreaDensity)) throw new ArgumentException("Expected type AreaDensity.", nameof(obj)); - - return CompareTo((AreaDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AreaDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is AreaDensity)) - return false; - - var objQuantity = (AreaDensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another AreaDensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(AreaDensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(AreaDensity other, AreaDensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaDensity. - public override int GetHashCode() - { - return new { type = typeof(AreaDensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaDensity to another AreaDensity with the unit representation . - /// - /// A AreaDensity with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaDensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AreaDensityUnit ToStringDefaultUnit { get; set; } = AreaDensityUnit.KilogramPerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AreaDensity - /// - public static AreaDensity MaxValue => new AreaDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AreaDensity - /// - public static AreaDensity MinValue => new AreaDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AreaDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs b/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs deleted file mode 100644 index 0019c55a2d..0000000000 --- a/Common/GeneratedCode/Quantities/AreaMomentOfInertia.Common.g.cs +++ /dev/null @@ -1,595 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A geometric property of an area that reflects how its points are distributed with regard to an axis. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class AreaMomentOfInertia : IQuantity -#else - public partial struct AreaMomentOfInertia : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaMomentOfInertiaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static AreaMomentOfInertia() - { - BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit MeterToTheFourth. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public AreaMomentOfInertia(double meterstothefourth) - { - _value = Convert.ToDouble(meterstothefourth); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - AreaMomentOfInertia(double numericValue, AreaMomentOfInertiaUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit MeterToTheFourth. - /// - /// Value assuming base unit MeterToTheFourth. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AreaMomentOfInertia(long meterstothefourth) : this(Convert.ToDouble(meterstothefourth), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit MeterToTheFourth. - /// - /// Value assuming base unit MeterToTheFourth. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - AreaMomentOfInertia(decimal meterstothefourth) : this(Convert.ToDouble(meterstothefourth), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the AreaMomentOfInertia quantity. - /// - public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); - - /// - /// Get AreaMomentOfInertia in CentimetersToTheFourth. - /// - public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in DecimetersToTheFourth. - /// - public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in FeetToTheFourth. - /// - public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); - - /// - /// Get AreaMomentOfInertia in InchesToTheFourth. - /// - public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); - - /// - /// Get AreaMomentOfInertia in MetersToTheFourth. - /// - public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); - - /// - /// Get AreaMomentOfInertia in MillimetersToTheFourth. - /// - public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. - /// - public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(0, BaseUnit); - - /// - /// Get AreaMomentOfInertia from CentimetersToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) -#else - public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) -#endif - { - double value = (double) centimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from DecimetersToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) -#else - public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) -#endif - { - double value = (double) decimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from FeetToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) -#else - public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) -#endif - { - double value = (double) feettothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from InchesToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) -#else - public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) -#endif - { - double value = (double) inchestothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from MetersToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) -#else - public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) -#endif - { - double value = (double) meterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); - } - - /// - /// Get AreaMomentOfInertia from MillimetersToTheFourth. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) -#else - public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) -#endif - { - double value = (double) millimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaMomentOfInertia unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) -#else - public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) -#endif - { - return new AreaMomentOfInertia((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is AreaMomentOfInertia)) throw new ArgumentException("Expected type AreaMomentOfInertia.", nameof(obj)); - - return CompareTo((AreaMomentOfInertia)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(AreaMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is AreaMomentOfInertia)) - return false; - - var objQuantity = (AreaMomentOfInertia)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another AreaMomentOfInertia by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(AreaMomentOfInertia, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(AreaMomentOfInertia other, AreaMomentOfInertia maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaMomentOfInertia. - public override int GetHashCode() - { - return new { type = typeof(AreaMomentOfInertia), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . - /// - /// A AreaMomentOfInertia with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return _value/1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return _value/1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return _value*Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return _value*Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return _value; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return _value/1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaMomentOfInertiaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return baseUnitValue*1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return baseUnitValue*1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return baseUnitValue/Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return baseUnitValue/Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return baseUnitValue; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return baseUnitValue*1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaMomentOfInertia Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is MeterToTheFourth - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static AreaMomentOfInertiaUnit ToStringDefaultUnit { get; set; } = AreaMomentOfInertiaUnit.MeterToTheFourth; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(AreaMomentOfInertiaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MaxValue => new AreaMomentOfInertia(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MinValue => new AreaMomentOfInertia(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => AreaMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/BitRate.Common.g.cs b/Common/GeneratedCode/Quantities/BitRate.Common.g.cs deleted file mode 100644 index 23bb99ca85..0000000000 --- a/Common/GeneratedCode/Quantities/BitRate.Common.g.cs +++ /dev/null @@ -1,1013 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class BitRate : IQuantity -#else - public partial struct BitRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BitRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static BitRate() - { - } - - /// - /// Creates the quantity with the given value in the base unit BitPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public BitRate(double bitspersecond) - { - _value = Convert.ToDecimal(bitspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - BitRate(decimal numericValue, BitRateUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit BitPerSecond. - /// - /// Value assuming base unit BitPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - BitRate(long bitspersecond) : this(Convert.ToDecimal(bitspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit BitPerSecond. - /// - /// Value assuming base unit BitPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - BitRate(decimal bitspersecond) : this(Convert.ToDecimal(bitspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.BitRate; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the BitRate quantity. - /// - public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); - - /// - /// Get BitRate in BitsPerSecond. - /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); - - /// - /// Get BitRate in BytesPerSecond. - /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); - - /// - /// Get BitRate in ExabitsPerSecond. - /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); - - /// - /// Get BitRate in ExabytesPerSecond. - /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); - - /// - /// Get BitRate in ExbibitsPerSecond. - /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); - - /// - /// Get BitRate in ExbibytesPerSecond. - /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); - - /// - /// Get BitRate in GibibitsPerSecond. - /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); - - /// - /// Get BitRate in GibibytesPerSecond. - /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); - - /// - /// Get BitRate in GigabitsPerSecond. - /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); - - /// - /// Get BitRate in GigabytesPerSecond. - /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); - - /// - /// Get BitRate in KibibitsPerSecond. - /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); - - /// - /// Get BitRate in KibibytesPerSecond. - /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); - - /// - /// Get BitRate in KilobitsPerSecond. - /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); - - /// - /// Get BitRate in KilobytesPerSecond. - /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); - - /// - /// Get BitRate in MebibitsPerSecond. - /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); - - /// - /// Get BitRate in MebibytesPerSecond. - /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); - - /// - /// Get BitRate in MegabitsPerSecond. - /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); - - /// - /// Get BitRate in MegabytesPerSecond. - /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); - - /// - /// Get BitRate in PebibitsPerSecond. - /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); - - /// - /// Get BitRate in PebibytesPerSecond. - /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); - - /// - /// Get BitRate in PetabitsPerSecond. - /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); - - /// - /// Get BitRate in PetabytesPerSecond. - /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); - - /// - /// Get BitRate in TebibitsPerSecond. - /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); - - /// - /// Get BitRate in TebibytesPerSecond. - /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); - - /// - /// Get BitRate in TerabitsPerSecond. - /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); - - /// - /// Get BitRate in TerabytesPerSecond. - /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. - /// - public static BitRate Zero => new BitRate(0, BaseUnit); - - /// - /// Get BitRate from BitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBitsPerSecond(double bitspersecond) -#else - public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) -#endif - { - decimal value = (decimal) bitspersecond; - return new BitRate(value, BitRateUnit.BitPerSecond); - } - - /// - /// Get BitRate from BytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBytesPerSecond(double bytespersecond) -#else - public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) -#endif - { - decimal value = (decimal) bytespersecond; - return new BitRate(value, BitRateUnit.BytePerSecond); - } - - /// - /// Get BitRate from ExabitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabitsPerSecond(double exabitspersecond) -#else - public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) -#endif - { - decimal value = (decimal) exabitspersecond; - return new BitRate(value, BitRateUnit.ExabitPerSecond); - } - - /// - /// Get BitRate from ExabytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabytesPerSecond(double exabytespersecond) -#else - public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) -#endif - { - decimal value = (decimal) exabytespersecond; - return new BitRate(value, BitRateUnit.ExabytePerSecond); - } - - /// - /// Get BitRate from ExbibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibitsPerSecond(double exbibitspersecond) -#else - public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) -#endif - { - decimal value = (decimal) exbibitspersecond; - return new BitRate(value, BitRateUnit.ExbibitPerSecond); - } - - /// - /// Get BitRate from ExbibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibytesPerSecond(double exbibytespersecond) -#else - public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) -#endif - { - decimal value = (decimal) exbibytespersecond; - return new BitRate(value, BitRateUnit.ExbibytePerSecond); - } - - /// - /// Get BitRate from GibibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibitsPerSecond(double gibibitspersecond) -#else - public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) -#endif - { - decimal value = (decimal) gibibitspersecond; - return new BitRate(value, BitRateUnit.GibibitPerSecond); - } - - /// - /// Get BitRate from GibibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibytesPerSecond(double gibibytespersecond) -#else - public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) -#endif - { - decimal value = (decimal) gibibytespersecond; - return new BitRate(value, BitRateUnit.GibibytePerSecond); - } - - /// - /// Get BitRate from GigabitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabitsPerSecond(double gigabitspersecond) -#else - public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) -#endif - { - decimal value = (decimal) gigabitspersecond; - return new BitRate(value, BitRateUnit.GigabitPerSecond); - } - - /// - /// Get BitRate from GigabytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabytesPerSecond(double gigabytespersecond) -#else - public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) -#endif - { - decimal value = (decimal) gigabytespersecond; - return new BitRate(value, BitRateUnit.GigabytePerSecond); - } - - /// - /// Get BitRate from KibibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibitsPerSecond(double kibibitspersecond) -#else - public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) -#endif - { - decimal value = (decimal) kibibitspersecond; - return new BitRate(value, BitRateUnit.KibibitPerSecond); - } - - /// - /// Get BitRate from KibibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibytesPerSecond(double kibibytespersecond) -#else - public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) -#endif - { - decimal value = (decimal) kibibytespersecond; - return new BitRate(value, BitRateUnit.KibibytePerSecond); - } - - /// - /// Get BitRate from KilobitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobitsPerSecond(double kilobitspersecond) -#else - public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) -#endif - { - decimal value = (decimal) kilobitspersecond; - return new BitRate(value, BitRateUnit.KilobitPerSecond); - } - - /// - /// Get BitRate from KilobytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobytesPerSecond(double kilobytespersecond) -#else - public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) -#endif - { - decimal value = (decimal) kilobytespersecond; - return new BitRate(value, BitRateUnit.KilobytePerSecond); - } - - /// - /// Get BitRate from MebibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibitsPerSecond(double mebibitspersecond) -#else - public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) -#endif - { - decimal value = (decimal) mebibitspersecond; - return new BitRate(value, BitRateUnit.MebibitPerSecond); - } - - /// - /// Get BitRate from MebibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibytesPerSecond(double mebibytespersecond) -#else - public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) -#endif - { - decimal value = (decimal) mebibytespersecond; - return new BitRate(value, BitRateUnit.MebibytePerSecond); - } - - /// - /// Get BitRate from MegabitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabitsPerSecond(double megabitspersecond) -#else - public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) -#endif - { - decimal value = (decimal) megabitspersecond; - return new BitRate(value, BitRateUnit.MegabitPerSecond); - } - - /// - /// Get BitRate from MegabytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabytesPerSecond(double megabytespersecond) -#else - public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) -#endif - { - decimal value = (decimal) megabytespersecond; - return new BitRate(value, BitRateUnit.MegabytePerSecond); - } - - /// - /// Get BitRate from PebibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibitsPerSecond(double pebibitspersecond) -#else - public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) -#endif - { - decimal value = (decimal) pebibitspersecond; - return new BitRate(value, BitRateUnit.PebibitPerSecond); - } - - /// - /// Get BitRate from PebibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibytesPerSecond(double pebibytespersecond) -#else - public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) -#endif - { - decimal value = (decimal) pebibytespersecond; - return new BitRate(value, BitRateUnit.PebibytePerSecond); - } - - /// - /// Get BitRate from PetabitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabitsPerSecond(double petabitspersecond) -#else - public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) -#endif - { - decimal value = (decimal) petabitspersecond; - return new BitRate(value, BitRateUnit.PetabitPerSecond); - } - - /// - /// Get BitRate from PetabytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabytesPerSecond(double petabytespersecond) -#else - public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) -#endif - { - decimal value = (decimal) petabytespersecond; - return new BitRate(value, BitRateUnit.PetabytePerSecond); - } - - /// - /// Get BitRate from TebibitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibitsPerSecond(double tebibitspersecond) -#else - public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) -#endif - { - decimal value = (decimal) tebibitspersecond; - return new BitRate(value, BitRateUnit.TebibitPerSecond); - } - - /// - /// Get BitRate from TebibytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibytesPerSecond(double tebibytespersecond) -#else - public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) -#endif - { - decimal value = (decimal) tebibytespersecond; - return new BitRate(value, BitRateUnit.TebibytePerSecond); - } - - /// - /// Get BitRate from TerabitsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabitsPerSecond(double terabitspersecond) -#else - public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) -#endif - { - decimal value = (decimal) terabitspersecond; - return new BitRate(value, BitRateUnit.TerabitPerSecond); - } - - /// - /// Get BitRate from TerabytesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabytesPerSecond(double terabytespersecond) -#else - public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) -#endif - { - decimal value = (decimal) terabytespersecond; - return new BitRate(value, BitRateUnit.TerabytePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BitRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BitRate From(double value, BitRateUnit fromUnit) -#else - public static BitRate From(QuantityValue value, BitRateUnit fromUnit) -#endif - { - return new BitRate((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BitRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is BitRate)) throw new ArgumentException("Expected type BitRate.", nameof(obj)); - - return CompareTo((BitRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(BitRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - public override bool Equals(object obj) - { - if(obj is null || !(obj is BitRate)) - return false; - - var objQuantity = (BitRate)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another BitRate by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(BitRate, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(BitRate other, BitRate maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BitRate. - public override int GetHashCode() - { - return new { type = typeof(BitRate), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BitRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BitRate to another BitRate with the unit representation . - /// - /// A BitRate with the specified unit. - public BitRate ToUnit(BitRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BitRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case BitRateUnit.BitPerSecond: return _value; - case BitRateUnit.BytePerSecond: return _value*8m; - case BitRateUnit.ExabitPerSecond: return (_value) * 1e18m; - case BitRateUnit.ExabytePerSecond: return (_value*8m) * 1e18m; - case BitRateUnit.ExbibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (_value) * (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (_value) * 1e9m; - case BitRateUnit.GigabytePerSecond: return (_value*8m) * 1e9m; - case BitRateUnit.KibibitPerSecond: return (_value) * 1024m; - case BitRateUnit.KibibytePerSecond: return (_value*8m) * 1024m; - case BitRateUnit.KilobitPerSecond: return (_value) * 1e3m; - case BitRateUnit.KilobytePerSecond: return (_value*8m) * 1e3m; - case BitRateUnit.MebibitPerSecond: return (_value) * (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (_value*8m) * (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (_value) * 1e6m; - case BitRateUnit.MegabytePerSecond: return (_value*8m) * 1e6m; - case BitRateUnit.PebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (_value) * 1e15m; - case BitRateUnit.PetabytePerSecond: return (_value*8m) * 1e15m; - case BitRateUnit.TebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (_value) * 1e12m; - case BitRateUnit.TerabytePerSecond: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(BitRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BitRateUnit.BitPerSecond: return baseUnitValue; - case BitRateUnit.BytePerSecond: return baseUnitValue/8m; - case BitRateUnit.ExabitPerSecond: return (baseUnitValue) / 1e18m; - case BitRateUnit.ExabytePerSecond: return (baseUnitValue/8m) / 1e18m; - case BitRateUnit.ExbibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (baseUnitValue) / 1e9m; - case BitRateUnit.GigabytePerSecond: return (baseUnitValue/8m) / 1e9m; - case BitRateUnit.KibibitPerSecond: return (baseUnitValue) / 1024m; - case BitRateUnit.KibibytePerSecond: return (baseUnitValue/8m) / 1024m; - case BitRateUnit.KilobitPerSecond: return (baseUnitValue) / 1e3m; - case BitRateUnit.KilobytePerSecond: return (baseUnitValue/8m) / 1e3m; - case BitRateUnit.MebibitPerSecond: return (baseUnitValue) / (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (baseUnitValue) / 1e6m; - case BitRateUnit.MegabytePerSecond: return (baseUnitValue/8m) / 1e6m; - case BitRateUnit.PebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (baseUnitValue) / 1e15m; - case BitRateUnit.PetabytePerSecond: return (baseUnitValue/8m) / 1e15m; - case BitRateUnit.TebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (baseUnitValue) / 1e12m; - case BitRateUnit.TerabytePerSecond: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BitRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BitRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BitRateUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is BitPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static BitRateUnit ToStringDefaultUnit { get; set; } = BitRateUnit.BitPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(BitRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of BitRate - /// - public static BitRate MaxValue => new BitRate(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of BitRate - /// - public static BitRate MinValue => new BitRate(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => BitRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BitRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs b/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs deleted file mode 100644 index 1fd284c02c..0000000000 --- a/Common/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class BrakeSpecificFuelConsumption : IQuantity -#else - public partial struct BrakeSpecificFuelConsumption : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BrakeSpecificFuelConsumptionUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static BrakeSpecificFuelConsumption() - { - BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerJoule. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public BrakeSpecificFuelConsumption(double kilogramsperjoule) - { - _value = Convert.ToDouble(kilogramsperjoule); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - BrakeSpecificFuelConsumption(double numericValue, BrakeSpecificFuelConsumptionUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerJoule. - /// - /// Value assuming base unit KilogramPerJoule. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - BrakeSpecificFuelConsumption(long kilogramsperjoule) : this(Convert.ToDouble(kilogramsperjoule), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerJoule. - /// - /// Value assuming base unit KilogramPerJoule. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - BrakeSpecificFuelConsumption(decimal kilogramsperjoule) : this(Convert.ToDouble(kilogramsperjoule), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the BrakeSpecificFuelConsumption quantity. - /// - public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); - - /// - /// Get BrakeSpecificFuelConsumption in GramsPerKiloWattHour. - /// - public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - - /// - /// Get BrakeSpecificFuelConsumption in KilogramsPerJoule. - /// - public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - - /// - /// Get BrakeSpecificFuelConsumption in PoundsPerMechanicalHorsepowerHour. - /// - public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. - /// - public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(0, BaseUnit); - - /// - /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) -#else - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) -#endif - { - double value = (double) gramsperkilowatthour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - } - - /// - /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) -#else - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) -#endif - { - double value = (double) kilogramsperjoule; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - } - - /// - /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) -#else - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) -#endif - { - double value = (double) poundspermechanicalhorsepowerhour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BrakeSpecificFuelConsumption unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) -#else - public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) -#endif - { - return new BrakeSpecificFuelConsumption((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is BrakeSpecificFuelConsumption)) throw new ArgumentException("Expected type BrakeSpecificFuelConsumption.", nameof(obj)); - - return CompareTo((BrakeSpecificFuelConsumption)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(BrakeSpecificFuelConsumption other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(BrakeSpecificFuelConsumption, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is BrakeSpecificFuelConsumption)) - return false; - - var objQuantity = (BrakeSpecificFuelConsumption)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another BrakeSpecificFuelConsumption by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(BrakeSpecificFuelConsumption, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BrakeSpecificFuelConsumption. - public override int GetHashCode() - { - return new { type = typeof(BrakeSpecificFuelConsumption), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . - /// - /// A BrakeSpecificFuelConsumption with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BrakeSpecificFuelConsumption(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return _value/3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return _value; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return _value*1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(BrakeSpecificFuelConsumptionUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return baseUnitValue*3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return baseUnitValue; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return baseUnitValue/1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BrakeSpecificFuelConsumption Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerJoule - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static BrakeSpecificFuelConsumptionUnit ToStringDefaultUnit { get; set; } = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(BrakeSpecificFuelConsumptionUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MaxValue => new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MinValue => new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs b/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs deleted file mode 100644 index 09f737ed23..0000000000 --- a/Common/GeneratedCode/Quantities/Capacitance.Common.g.cs +++ /dev/null @@ -1,574 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Capacitance is the ability of a body to store an electric charge. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Capacitance : IQuantity -#else - public partial struct Capacitance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CapacitanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Capacitance() - { - BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Farad. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Capacitance(double farads) - { - _value = Convert.ToDouble(farads); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Capacitance(double numericValue, CapacitanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Farad. - /// - /// Value assuming base unit Farad. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Capacitance(long farads) : this(Convert.ToDouble(farads), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Farad. - /// - /// Value assuming base unit Farad. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Capacitance(decimal farads) : this(Convert.ToDouble(farads), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Capacitance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Capacitance quantity. - /// - public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); - - /// - /// Get Capacitance in Farads. - /// - public double Farads => As(CapacitanceUnit.Farad); - - /// - /// Get Capacitance in Microfarads. - /// - public double Microfarads => As(CapacitanceUnit.Microfarad); - - /// - /// Get Capacitance in Millifarads. - /// - public double Millifarads => As(CapacitanceUnit.Millifarad); - - /// - /// Get Capacitance in Nanofarads. - /// - public double Nanofarads => As(CapacitanceUnit.Nanofarad); - - /// - /// Get Capacitance in Picofarads. - /// - public double Picofarads => As(CapacitanceUnit.Picofarad); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Farad. - /// - public static Capacitance Zero => new Capacitance(0, BaseUnit); - - /// - /// Get Capacitance from Farads. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromFarads(double farads) -#else - public static Capacitance FromFarads(QuantityValue farads) -#endif - { - double value = (double) farads; - return new Capacitance(value, CapacitanceUnit.Farad); - } - - /// - /// Get Capacitance from Microfarads. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromMicrofarads(double microfarads) -#else - public static Capacitance FromMicrofarads(QuantityValue microfarads) -#endif - { - double value = (double) microfarads; - return new Capacitance(value, CapacitanceUnit.Microfarad); - } - - /// - /// Get Capacitance from Millifarads. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromMillifarads(double millifarads) -#else - public static Capacitance FromMillifarads(QuantityValue millifarads) -#endif - { - double value = (double) millifarads; - return new Capacitance(value, CapacitanceUnit.Millifarad); - } - - /// - /// Get Capacitance from Nanofarads. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromNanofarads(double nanofarads) -#else - public static Capacitance FromNanofarads(QuantityValue nanofarads) -#endif - { - double value = (double) nanofarads; - return new Capacitance(value, CapacitanceUnit.Nanofarad); - } - - /// - /// Get Capacitance from Picofarads. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromPicofarads(double picofarads) -#else - public static Capacitance FromPicofarads(QuantityValue picofarads) -#endif - { - 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. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Capacitance From(double value, CapacitanceUnit fromUnit) -#else - public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) -#endif - { - return new Capacitance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(CapacitanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Capacitance)) throw new ArgumentException("Expected type Capacitance.", nameof(obj)); - - return CompareTo((Capacitance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Capacitance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Capacitance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Capacitance)) - return false; - - var objQuantity = (Capacitance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Capacitance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Capacitance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Capacitance other, Capacitance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Capacitance. - public override int GetHashCode() - { - return new { type = typeof(Capacitance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CapacitanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Capacitance to another Capacitance with the unit representation . - /// - /// A Capacitance with the specified unit. - public Capacitance ToUnit(CapacitanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Capacitance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case CapacitanceUnit.Farad: return _value; - 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.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 Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Capacitance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Capacitance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CapacitanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Farad - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static CapacitanceUnit ToStringDefaultUnit { get; set; } = CapacitanceUnit.Farad; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(CapacitanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Capacitance - /// - public static Capacitance MaxValue => new Capacitance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Capacitance - /// - public static Capacitance MinValue => new Capacitance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Capacitance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Capacitance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/CoefficientOfThermalExpansion.Common.g.cs b/Common/GeneratedCode/Quantities/CoefficientOfThermalExpansion.Common.g.cs deleted file mode 100644 index c4590533c0..0000000000 --- a/Common/GeneratedCode/Quantities/CoefficientOfThermalExpansion.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A unit that represents a fractional change in size in response to a change in temperature. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class CoefficientOfThermalExpansion : IQuantity -#else - public partial struct CoefficientOfThermalExpansion : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CoefficientOfThermalExpansionUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static CoefficientOfThermalExpansion() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit InverseKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public CoefficientOfThermalExpansion(double inversekelvin) - { - _value = Convert.ToDouble(inversekelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - CoefficientOfThermalExpansion(double numericValue, CoefficientOfThermalExpansionUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit InverseKelvin. - /// - /// Value assuming base unit InverseKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - CoefficientOfThermalExpansion(long inversekelvin) : this(Convert.ToDouble(inversekelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit InverseKelvin. - /// - /// Value assuming base unit InverseKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - CoefficientOfThermalExpansion(decimal inversekelvin) : this(Convert.ToDouble(inversekelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.CoefficientOfThermalExpansion; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static CoefficientOfThermalExpansionUnit BaseUnit => CoefficientOfThermalExpansionUnit.InverseKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the CoefficientOfThermalExpansion quantity. - /// - public static CoefficientOfThermalExpansionUnit[] Units { get; } = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); - - /// - /// Get CoefficientOfThermalExpansion in InverseDegreeCelsius. - /// - public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - - /// - /// Get CoefficientOfThermalExpansion in InverseDegreeFahrenheit. - /// - public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - - /// - /// Get CoefficientOfThermalExpansion in InverseKelvin. - /// - public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. - /// - public static CoefficientOfThermalExpansion Zero => new CoefficientOfThermalExpansion(0, BaseUnit); - - /// - /// Get CoefficientOfThermalExpansion from InverseDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(double inversedegreecelsius) -#else - public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius) -#endif - { - double value = (double) inversedegreecelsius; - return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - } - - /// - /// Get CoefficientOfThermalExpansion from InverseDegreeFahrenheit. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(double inversedegreefahrenheit) -#else - public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit) -#endif - { - double value = (double) inversedegreefahrenheit; - return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - } - - /// - /// Get CoefficientOfThermalExpansion from InverseKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseKelvin(double inversekelvin) -#else - public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin) -#endif - { - 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. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static CoefficientOfThermalExpansion From(double value, CoefficientOfThermalExpansionUnit fromUnit) -#else - public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) -#endif - { - return new CoefficientOfThermalExpansion((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is CoefficientOfThermalExpansion)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); - - return CompareTo((CoefficientOfThermalExpansion)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(CoefficientOfThermalExpansion other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(CoefficientOfThermalExpansion, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is CoefficientOfThermalExpansion)) - return false; - - var objQuantity = (CoefficientOfThermalExpansion)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another CoefficientOfThermalExpansion by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(CoefficientOfThermalExpansion, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current CoefficientOfThermalExpansion. - public override int GetHashCode() - { - return new { type = typeof(CoefficientOfThermalExpansion), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CoefficientOfThermalExpansionUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . - /// - /// A CoefficientOfThermalExpansion with the specified unit. - public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new CoefficientOfThermalExpansion(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*5/9; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*9/5; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static CoefficientOfThermalExpansion Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out CoefficientOfThermalExpansion result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CoefficientOfThermalExpansionUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is InverseKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static CoefficientOfThermalExpansionUnit ToStringDefaultUnit { get; set; } = CoefficientOfThermalExpansionUnit.InverseKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(CoefficientOfThermalExpansionUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of CoefficientOfThermalExpansion - /// - public static CoefficientOfThermalExpansion MaxValue => new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of CoefficientOfThermalExpansion - /// - public static CoefficientOfThermalExpansion MinValue => new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Density.Common.g.cs b/Common/GeneratedCode/Quantities/Density.Common.g.cs deleted file mode 100644 index e6b53a129f..0000000000 --- a/Common/GeneratedCode/Quantities/Density.Common.g.cs +++ /dev/null @@ -1,1267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Density : IQuantity -#else - public partial struct Density : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Density() - { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerCubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Density(double kilogramspercubicmeter) - { - _value = Convert.ToDouble(kilogramspercubicmeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Density(double numericValue, DensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerCubicMeter. - /// - /// Value assuming base unit KilogramPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Density(long kilogramspercubicmeter) : this(Convert.ToDouble(kilogramspercubicmeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerCubicMeter. - /// - /// Value assuming base unit KilogramPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Density(decimal kilogramspercubicmeter) : this(Convert.ToDouble(kilogramspercubicmeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Density; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Density quantity. - /// - public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); - - /// - /// Get Density in CentigramsPerDeciLiter. - /// - public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); - - /// - /// Get Density in CentigramsPerLiter. - /// - public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); - - /// - /// Get Density in CentigramsPerMilliliter. - /// - public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); - - /// - /// Get Density in DecigramsPerDeciLiter. - /// - public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); - - /// - /// Get Density in DecigramsPerLiter. - /// - public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); - - /// - /// Get Density in DecigramsPerMilliliter. - /// - public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); - - /// - /// Get Density in GramsPerCubicCentimeter. - /// - public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); - - /// - /// Get Density in GramsPerCubicMeter. - /// - public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); - - /// - /// Get Density in GramsPerCubicMillimeter. - /// - public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); - - /// - /// Get Density in GramsPerDeciLiter. - /// - public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); - - /// - /// Get Density in GramsPerLiter. - /// - public double GramsPerLiter => As(DensityUnit.GramPerLiter); - - /// - /// Get Density in GramsPerMilliliter. - /// - public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); - - /// - /// Get Density in KilogramsPerCubicCentimeter. - /// - public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); - - /// - /// Get Density in KilogramsPerCubicMeter. - /// - public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); - - /// - /// Get Density in KilogramsPerCubicMillimeter. - /// - public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); - - /// - /// Get Density in KilopoundsPerCubicFoot. - /// - public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); - - /// - /// Get Density in KilopoundsPerCubicInch. - /// - public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); - - /// - /// Get Density in MicrogramsPerDeciLiter. - /// - public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); - - /// - /// Get Density in MicrogramsPerLiter. - /// - public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); - - /// - /// Get Density in MicrogramsPerMilliliter. - /// - public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); - - /// - /// Get Density in MilligramsPerCubicMeter. - /// - public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); - - /// - /// Get Density in MilligramsPerDeciLiter. - /// - public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); - - /// - /// Get Density in MilligramsPerLiter. - /// - public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); - - /// - /// Get Density in MilligramsPerMilliliter. - /// - public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); - - /// - /// Get Density in NanogramsPerDeciLiter. - /// - public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); - - /// - /// Get Density in NanogramsPerLiter. - /// - public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); - - /// - /// Get Density in NanogramsPerMilliliter. - /// - public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); - - /// - /// Get Density in PicogramsPerDeciLiter. - /// - public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); - - /// - /// Get Density in PicogramsPerLiter. - /// - public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); - - /// - /// Get Density in PicogramsPerMilliliter. - /// - public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); - - /// - /// Get Density in PoundsPerCubicFoot. - /// - public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); - - /// - /// Get Density in PoundsPerCubicInch. - /// - public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); - - /// - /// Get Density in PoundsPerImperialGallon. - /// - public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); - - /// - /// Get Density in PoundsPerUSGallon. - /// - public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); - - /// - /// Get Density in SlugsPerCubicFoot. - /// - public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); - - /// - /// Get Density in TonnesPerCubicCentimeter. - /// - public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); - - /// - /// Get Density in TonnesPerCubicMeter. - /// - public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); - - /// - /// Get Density in TonnesPerCubicMillimeter. - /// - public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - public static Density Zero => new Density(0, BaseUnit); - - /// - /// Get Density from CentigramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) -#else - public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) -#endif - { - double value = (double) centigramsperdeciliter; - return new Density(value, DensityUnit.CentigramPerDeciliter); - } - - /// - /// Get Density from CentigramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerLiter(double centigramsperliter) -#else - public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) -#endif - { - double value = (double) centigramsperliter; - return new Density(value, DensityUnit.CentigramPerLiter); - } - - /// - /// Get Density from CentigramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) -#else - public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) -#endif - { - double value = (double) centigramspermilliliter; - return new Density(value, DensityUnit.CentigramPerMilliliter); - } - - /// - /// Get Density from DecigramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) -#else - public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) -#endif - { - double value = (double) decigramsperdeciliter; - return new Density(value, DensityUnit.DecigramPerDeciliter); - } - - /// - /// Get Density from DecigramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerLiter(double decigramsperliter) -#else - public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) -#endif - { - double value = (double) decigramsperliter; - return new Density(value, DensityUnit.DecigramPerLiter); - } - - /// - /// Get Density from DecigramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) -#else - public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) -#endif - { - double value = (double) decigramspermilliliter; - return new Density(value, DensityUnit.DecigramPerMilliliter); - } - - /// - /// Get Density from GramsPerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) -#else - public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) -#endif - { - double value = (double) gramspercubiccentimeter; - return new Density(value, DensityUnit.GramPerCubicCentimeter); - } - - /// - /// Get Density from GramsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMeter(double gramspercubicmeter) -#else - public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) -#endif - { - double value = (double) gramspercubicmeter; - return new Density(value, DensityUnit.GramPerCubicMeter); - } - - /// - /// Get Density from GramsPerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) -#else - public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) -#endif - { - double value = (double) gramspercubicmillimeter; - return new Density(value, DensityUnit.GramPerCubicMillimeter); - } - - /// - /// Get Density from GramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerDeciLiter(double gramsperdeciliter) -#else - public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) -#endif - { - double value = (double) gramsperdeciliter; - return new Density(value, DensityUnit.GramPerDeciliter); - } - - /// - /// Get Density from GramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerLiter(double gramsperliter) -#else - public static Density FromGramsPerLiter(QuantityValue gramsperliter) -#endif - { - double value = (double) gramsperliter; - return new Density(value, DensityUnit.GramPerLiter); - } - - /// - /// Get Density from GramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerMilliliter(double gramspermilliliter) -#else - public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) -#endif - { - double value = (double) gramspermilliliter; - return new Density(value, DensityUnit.GramPerMilliliter); - } - - /// - /// Get Density from KilogramsPerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) -#else - public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) -#endif - { - double value = (double) kilogramspercubiccentimeter; - return new Density(value, DensityUnit.KilogramPerCubicCentimeter); - } - - /// - /// Get Density from KilogramsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) -#else - public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) -#endif - { - double value = (double) kilogramspercubicmeter; - return new Density(value, DensityUnit.KilogramPerCubicMeter); - } - - /// - /// Get Density from KilogramsPerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) -#else - public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) -#endif - { - double value = (double) kilogramspercubicmillimeter; - return new Density(value, DensityUnit.KilogramPerCubicMillimeter); - } - - /// - /// Get Density from KilopoundsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) -#else - public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) -#endif - { - double value = (double) kilopoundspercubicfoot; - return new Density(value, DensityUnit.KilopoundPerCubicFoot); - } - - /// - /// Get Density from KilopoundsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) -#else - public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) -#endif - { - double value = (double) kilopoundspercubicinch; - return new Density(value, DensityUnit.KilopoundPerCubicInch); - } - - /// - /// Get Density from MicrogramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) -#else - public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) -#endif - { - double value = (double) microgramsperdeciliter; - return new Density(value, DensityUnit.MicrogramPerDeciliter); - } - - /// - /// Get Density from MicrogramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerLiter(double microgramsperliter) -#else - public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) -#endif - { - double value = (double) microgramsperliter; - return new Density(value, DensityUnit.MicrogramPerLiter); - } - - /// - /// Get Density from MicrogramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) -#else - public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) -#endif - { - double value = (double) microgramspermilliliter; - return new Density(value, DensityUnit.MicrogramPerMilliliter); - } - - /// - /// Get Density from MilligramsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) -#else - public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) -#endif - { - double value = (double) milligramspercubicmeter; - return new Density(value, DensityUnit.MilligramPerCubicMeter); - } - - /// - /// Get Density from MilligramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) -#else - public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) -#endif - { - double value = (double) milligramsperdeciliter; - return new Density(value, DensityUnit.MilligramPerDeciliter); - } - - /// - /// Get Density from MilligramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerLiter(double milligramsperliter) -#else - public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) -#endif - { - double value = (double) milligramsperliter; - return new Density(value, DensityUnit.MilligramPerLiter); - } - - /// - /// Get Density from MilligramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) -#else - public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) -#endif - { - double value = (double) milligramspermilliliter; - return new Density(value, DensityUnit.MilligramPerMilliliter); - } - - /// - /// Get Density from NanogramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) -#else - public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) -#endif - { - double value = (double) nanogramsperdeciliter; - return new Density(value, DensityUnit.NanogramPerDeciliter); - } - - /// - /// Get Density from NanogramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerLiter(double nanogramsperliter) -#else - public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) -#endif - { - double value = (double) nanogramsperliter; - return new Density(value, DensityUnit.NanogramPerLiter); - } - - /// - /// Get Density from NanogramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) -#else - public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) -#endif - { - double value = (double) nanogramspermilliliter; - return new Density(value, DensityUnit.NanogramPerMilliliter); - } - - /// - /// Get Density from PicogramsPerDeciLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) -#else - public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) -#endif - { - double value = (double) picogramsperdeciliter; - return new Density(value, DensityUnit.PicogramPerDeciliter); - } - - /// - /// Get Density from PicogramsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerLiter(double picogramsperliter) -#else - public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) -#endif - { - double value = (double) picogramsperliter; - return new Density(value, DensityUnit.PicogramPerLiter); - } - - /// - /// Get Density from PicogramsPerMilliliter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) -#else - public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) -#endif - { - double value = (double) picogramspermilliliter; - return new Density(value, DensityUnit.PicogramPerMilliliter); - } - - /// - /// Get Density from PoundsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) -#else - public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) -#endif - { - double value = (double) poundspercubicfoot; - return new Density(value, DensityUnit.PoundPerCubicFoot); - } - - /// - /// Get Density from PoundsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicInch(double poundspercubicinch) -#else - public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) -#endif - { - double value = (double) poundspercubicinch; - return new Density(value, DensityUnit.PoundPerCubicInch); - } - - /// - /// Get Density from PoundsPerImperialGallon. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) -#else - public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) -#endif - { - double value = (double) poundsperimperialgallon; - return new Density(value, DensityUnit.PoundPerImperialGallon); - } - - /// - /// Get Density from PoundsPerUSGallon. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerUSGallon(double poundsperusgallon) -#else - public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) -#endif - { - double value = (double) poundsperusgallon; - return new Density(value, DensityUnit.PoundPerUSGallon); - } - - /// - /// Get Density from SlugsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) -#else - public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) -#endif - { - double value = (double) slugspercubicfoot; - return new Density(value, DensityUnit.SlugPerCubicFoot); - } - - /// - /// Get Density from TonnesPerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) -#else - public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) -#endif - { - double value = (double) tonnespercubiccentimeter; - return new Density(value, DensityUnit.TonnePerCubicCentimeter); - } - - /// - /// Get Density from TonnesPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) -#else - public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) -#endif - { - double value = (double) tonnespercubicmeter; - return new Density(value, DensityUnit.TonnePerCubicMeter); - } - - /// - /// Get Density from TonnesPerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) -#else - public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) -#endif - { - double value = (double) tonnespercubicmillimeter; - return new Density(value, DensityUnit.TonnePerCubicMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Density unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Density From(double value, DensityUnit fromUnit) -#else - public static Density From(QuantityValue value, DensityUnit fromUnit) -#endif - { - return new Density((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Density)) throw new ArgumentException("Expected type Density.", nameof(obj)); - - return CompareTo((Density)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Density other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Density, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Density)) - return false; - - var objQuantity = (Density)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Density by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Density, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Density other, Density maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Density. - public override int GetHashCode() - { - return new { type = typeof(Density), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Density to another Density with the unit representation . - /// - /// A Density with the specified unit. - public Density ToUnit(DensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Density(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; - case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; - case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; - case DensityUnit.GramPerCubicMeter: return _value/1e3; - case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; - case DensityUnit.GramPerDeciliter: return _value/1e-1; - case DensityUnit.GramPerLiter: return _value/1; - case DensityUnit.GramPerMilliliter: return _value/1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; - case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; - case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; - case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; - case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; - case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; - case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; - case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; - case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; - case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; - case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; - case DensityUnit.SlugPerCubicFoot: return _value*515.378818; - case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; - case DensityUnit.TonnePerCubicMeter: return _value/0.001; - case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; - case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; - case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; - case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; - case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; - case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; - case DensityUnit.GramPerLiter: return baseUnitValue*1; - case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; - case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; - case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; - case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; - case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; - case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; - case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; - case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; - case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; - case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; - case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; - case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; - case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; - case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; - case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Density Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Density result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerCubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static DensityUnit ToStringDefaultUnit { get; set; } = DensityUnit.KilogramPerCubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Density - /// - public static Density MaxValue => new Density(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Density - /// - public static Density MinValue => new Density(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Density.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Density.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Duration.Common.g.cs b/Common/GeneratedCode/Quantities/Duration.Common.g.cs deleted file mode 100644 index dba1146018..0000000000 --- a/Common/GeneratedCode/Quantities/Duration.Common.g.cs +++ /dev/null @@ -1,725 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Duration : IQuantity -#else - public partial struct Duration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DurationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Duration() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Second. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Duration(double seconds) - { - _value = Convert.ToDouble(seconds); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Duration(double numericValue, DurationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Second. - /// - /// Value assuming base unit Second. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Duration(long seconds) : this(Convert.ToDouble(seconds), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Second. - /// - /// Value assuming base unit Second. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Duration(decimal seconds) : this(Convert.ToDouble(seconds), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Duration; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static DurationUnit BaseUnit => DurationUnit.Second; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Duration quantity. - /// - public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); - - /// - /// Get Duration in Days. - /// - public double Days => As(DurationUnit.Day); - - /// - /// Get Duration in Hours. - /// - public double Hours => As(DurationUnit.Hour); - - /// - /// Get Duration in Microseconds. - /// - public double Microseconds => As(DurationUnit.Microsecond); - - /// - /// Get Duration in Milliseconds. - /// - public double Milliseconds => As(DurationUnit.Millisecond); - - /// - /// Get Duration in Minutes. - /// - public double Minutes => As(DurationUnit.Minute); - - /// - /// Get Duration in Months. - /// - [System.Obsolete("Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.")] - public double Months => As(DurationUnit.Month); - - /// - /// Get Duration in Months30. - /// - public double Months30 => As(DurationUnit.Month30); - - /// - /// Get Duration in Nanoseconds. - /// - public double Nanoseconds => As(DurationUnit.Nanosecond); - - /// - /// Get Duration in Seconds. - /// - public double Seconds => As(DurationUnit.Second); - - /// - /// Get Duration in Weeks. - /// - public double Weeks => As(DurationUnit.Week); - - /// - /// Get Duration in Years. - /// - [System.Obsolete("Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.")] - public double Years => As(DurationUnit.Year); - - /// - /// Get Duration in Years365. - /// - public double Years365 => As(DurationUnit.Year365); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Second. - /// - public static Duration Zero => new Duration(0, BaseUnit); - - /// - /// Get Duration from Days. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromDays(double days) -#else - public static Duration FromDays(QuantityValue days) -#endif - { - double value = (double) days; - return new Duration(value, DurationUnit.Day); - } - - /// - /// Get Duration from Hours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromHours(double hours) -#else - public static Duration FromHours(QuantityValue hours) -#endif - { - double value = (double) hours; - return new Duration(value, DurationUnit.Hour); - } - - /// - /// Get Duration from Microseconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMicroseconds(double microseconds) -#else - public static Duration FromMicroseconds(QuantityValue microseconds) -#endif - { - double value = (double) microseconds; - return new Duration(value, DurationUnit.Microsecond); - } - - /// - /// Get Duration from Milliseconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMilliseconds(double milliseconds) -#else - public static Duration FromMilliseconds(QuantityValue milliseconds) -#endif - { - double value = (double) milliseconds; - return new Duration(value, DurationUnit.Millisecond); - } - - /// - /// Get Duration from Minutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMinutes(double minutes) -#else - public static Duration FromMinutes(QuantityValue minutes) -#endif - { - double value = (double) minutes; - return new Duration(value, DurationUnit.Minute); - } - - /// - /// Get Duration from Months. - /// - [System.Obsolete("Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMonths(double months) -#else - public static Duration FromMonths(QuantityValue months) -#endif - { - double value = (double) months; - return new Duration(value, DurationUnit.Month); - } - - /// - /// Get Duration from Months30. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMonths30(double months30) -#else - public static Duration FromMonths30(QuantityValue months30) -#endif - { - double value = (double) months30; - return new Duration(value, DurationUnit.Month30); - } - - /// - /// Get Duration from Nanoseconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromNanoseconds(double nanoseconds) -#else - public static Duration FromNanoseconds(QuantityValue nanoseconds) -#endif - { - double value = (double) nanoseconds; - return new Duration(value, DurationUnit.Nanosecond); - } - - /// - /// Get Duration from Seconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromSeconds(double seconds) -#else - public static Duration FromSeconds(QuantityValue seconds) -#endif - { - double value = (double) seconds; - return new Duration(value, DurationUnit.Second); - } - - /// - /// Get Duration from Weeks. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromWeeks(double weeks) -#else - public static Duration FromWeeks(QuantityValue weeks) -#endif - { - double value = (double) weeks; - return new Duration(value, DurationUnit.Week); - } - - /// - /// Get Duration from Years. - /// - [System.Obsolete("Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromYears(double years) -#else - public static Duration FromYears(QuantityValue years) -#endif - { - double value = (double) years; - return new Duration(value, DurationUnit.Year); - } - - /// - /// Get Duration from Years365. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromYears365(double years365) -#else - public static Duration FromYears365(QuantityValue years365) -#endif - { - double value = (double) years365; - return new Duration(value, DurationUnit.Year365); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Duration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Duration From(double value, DurationUnit fromUnit) -#else - public static Duration From(QuantityValue value, DurationUnit fromUnit) -#endif - { - return new Duration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DurationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Duration)) throw new ArgumentException("Expected type Duration.", nameof(obj)); - - return CompareTo((Duration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Duration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Duration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Duration)) - return false; - - var objQuantity = (Duration)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Duration by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Duration, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Duration other, Duration maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Duration. - public override int GetHashCode() - { - return new { type = typeof(Duration), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DurationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Duration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DurationUnit.Day: return _value*24*3600; - case DurationUnit.Hour: return _value*3600; - case DurationUnit.Microsecond: return (_value) * 1e-6d; - case DurationUnit.Millisecond: return (_value) * 1e-3d; - case DurationUnit.Minute: return _value*60; - case DurationUnit.Month: return _value*30*24*3600; - 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.Year: return _value*365*24*3600; - case DurationUnit.Year365: return _value*365*24*3600; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DurationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DurationUnit.Day: return baseUnitValue/(24*3600); - case DurationUnit.Hour: return baseUnitValue/3600; - case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; - case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; - case DurationUnit.Minute: return baseUnitValue/60; - case DurationUnit.Month: return baseUnitValue/(30*24*3600); - 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.Year: return baseUnitValue/(365*24*3600); - case DurationUnit.Year365: return baseUnitValue/(365*24*3600); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Duration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Duration result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DurationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Second - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static DurationUnit ToStringDefaultUnit { get; set; } = DurationUnit.Second; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DurationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Duration - /// - public static Duration MaxValue => new Duration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Duration - /// - public static Duration MinValue => new Duration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Duration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Duration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs b/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs deleted file mode 100644 index 778279d582..0000000000 --- a/Common/GeneratedCode/Quantities/DynamicViscosity.Common.g.cs +++ /dev/null @@ -1,595 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class DynamicViscosity : IQuantity -#else - public partial struct DynamicViscosity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DynamicViscosityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static DynamicViscosity() - { - BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonSecondPerMeterSquared. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public DynamicViscosity(double newtonsecondspermetersquared) - { - _value = Convert.ToDouble(newtonsecondspermetersquared); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - DynamicViscosity(double numericValue, DynamicViscosityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonSecondPerMeterSquared. - /// - /// Value assuming base unit NewtonSecondPerMeterSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - DynamicViscosity(long newtonsecondspermetersquared) : this(Convert.ToDouble(newtonsecondspermetersquared), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonSecondPerMeterSquared. - /// - /// Value assuming base unit NewtonSecondPerMeterSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - DynamicViscosity(decimal newtonsecondspermetersquared) : this(Convert.ToDouble(newtonsecondspermetersquared), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.DynamicViscosity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the DynamicViscosity quantity. - /// - public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); - - /// - /// Get DynamicViscosity in Centipoise. - /// - public double Centipoise => As(DynamicViscosityUnit.Centipoise); - - /// - /// Get DynamicViscosity in MicropascalSeconds. - /// - public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); - - /// - /// Get DynamicViscosity in MillipascalSeconds. - /// - public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); - - /// - /// Get DynamicViscosity in NewtonSecondsPerMeterSquared. - /// - public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); - - /// - /// Get DynamicViscosity in PascalSeconds. - /// - public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); - - /// - /// Get DynamicViscosity in Poise. - /// - public double Poise => As(DynamicViscosityUnit.Poise); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. - /// - public static DynamicViscosity Zero => new DynamicViscosity(0, BaseUnit); - - /// - /// Get DynamicViscosity from Centipoise. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromCentipoise(double centipoise) -#else - public static DynamicViscosity FromCentipoise(QuantityValue centipoise) -#endif - { - double value = (double) centipoise; - return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); - } - - /// - /// Get DynamicViscosity from MicropascalSeconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) -#else - public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) -#endif - { - double value = (double) micropascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); - } - - /// - /// Get DynamicViscosity from MillipascalSeconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) -#else - public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) -#endif - { - double value = (double) millipascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); - } - - /// - /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) -#else - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) -#endif - { - double value = (double) newtonsecondspermetersquared; - return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); - } - - /// - /// Get DynamicViscosity from PascalSeconds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPascalSeconds(double pascalseconds) -#else - public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) -#endif - { - double value = (double) pascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); - } - - /// - /// Get DynamicViscosity from Poise. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoise(double poise) -#else - public static DynamicViscosity FromPoise(QuantityValue poise) -#endif - { - double value = (double) poise; - return new DynamicViscosity(value, DynamicViscosityUnit.Poise); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// DynamicViscosity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) -#else - public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) -#endif - { - return new DynamicViscosity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DynamicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is DynamicViscosity)) throw new ArgumentException("Expected type DynamicViscosity.", nameof(obj)); - - return CompareTo((DynamicViscosity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(DynamicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(DynamicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is DynamicViscosity)) - return false; - - var objQuantity = (DynamicViscosity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another DynamicViscosity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(DynamicViscosity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(DynamicViscosity other, DynamicViscosity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current DynamicViscosity. - public override int GetHashCode() - { - return new { type = typeof(DynamicViscosity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . - /// - /// A DynamicViscosity with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new DynamicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; - case DynamicViscosityUnit.PascalSecond: return _value; - case DynamicViscosityUnit.Poise: return _value/10; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DynamicViscosityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; - case DynamicViscosityUnit.PascalSecond: return baseUnitValue; - case DynamicViscosityUnit.Poise: return baseUnitValue*10; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static DynamicViscosity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DynamicViscosityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonSecondPerMeterSquared - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static DynamicViscosityUnit ToStringDefaultUnit { get; set; } = DynamicViscosityUnit.NewtonSecondPerMeterSquared; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(DynamicViscosityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of DynamicViscosity - /// - public static DynamicViscosity MaxValue => new DynamicViscosity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of DynamicViscosity - /// - public static DynamicViscosity MinValue => new DynamicViscosity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => DynamicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs deleted file mode 100644 index 5f7caa94c2..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricAdmittance.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricAdmittance : IQuantity -#else - public partial struct ElectricAdmittance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricAdmittanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricAdmittance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Siemens. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricAdmittance(double siemens) - { - _value = Convert.ToDouble(siemens); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricAdmittance(double numericValue, ElectricAdmittanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Siemens. - /// - /// Value assuming base unit Siemens. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricAdmittance(long siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Siemens. - /// - /// Value assuming base unit Siemens. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricAdmittance(decimal siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricAdmittance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricAdmittance quantity. - /// - public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricAdmittance in Microsiemens. - /// - public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); - - /// - /// Get ElectricAdmittance in Millisiemens. - /// - public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); - - /// - /// Get ElectricAdmittance in Nanosiemens. - /// - public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); - - /// - /// Get ElectricAdmittance in Siemens. - /// - public double Siemens => As(ElectricAdmittanceUnit.Siemens); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricAdmittance Zero => new ElectricAdmittance(0, BaseUnit); - - /// - /// Get ElectricAdmittance from Microsiemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMicrosiemens(double microsiemens) -#else - public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) -#endif - { - double value = (double) microsiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); - } - - /// - /// Get ElectricAdmittance from Millisiemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMillisiemens(double millisiemens) -#else - public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) -#endif - { - double value = (double) millisiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); - } - - /// - /// Get ElectricAdmittance from Nanosiemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromNanosiemens(double nanosiemens) -#else - public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) -#endif - { - double value = (double) nanosiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); - } - - /// - /// Get ElectricAdmittance from Siemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromSiemens(double siemens) -#else - public static ElectricAdmittance FromSiemens(QuantityValue siemens) -#endif - { - double value = (double) siemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricAdmittance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromUnit) -#else - public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) -#endif - { - return new ElectricAdmittance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricAdmittanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricAdmittance)) throw new ArgumentException("Expected type ElectricAdmittance.", nameof(obj)); - - return CompareTo((ElectricAdmittance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricAdmittance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricAdmittance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricAdmittance)) - return false; - - var objQuantity = (ElectricAdmittance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricAdmittance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricAdmittance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricAdmittance other, ElectricAdmittance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricAdmittance. - public override int GetHashCode() - { - return new { type = typeof(ElectricAdmittance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . - /// - /// A ElectricAdmittance with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricAdmittance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (_value) * 1e-9d; - case ElectricAdmittanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricAdmittanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (baseUnitValue) / 1e-9d; - case ElectricAdmittanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricAdmittance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricAdmittanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Siemens - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricAdmittanceUnit ToStringDefaultUnit { get; set; } = ElectricAdmittanceUnit.Siemens; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricAdmittanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MaxValue => new ElectricAdmittance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MinValue => new ElectricAdmittance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricAdmittance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs deleted file mode 100644 index f354e89637..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCharge.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCharge : IQuantity -#else - public partial struct ElectricCharge : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCharge() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Coulomb. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricCharge(double coulombs) - { - _value = Convert.ToDouble(coulombs); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCharge(double numericValue, ElectricChargeUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Coulomb. - /// - /// Value assuming base unit Coulomb. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCharge(long coulombs) : this(Convert.ToDouble(coulombs), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Coulomb. - /// - /// Value assuming base unit Coulomb. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCharge(decimal coulombs) : this(Convert.ToDouble(coulombs), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCharge; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCharge quantity. - /// - public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCharge in Coulombs. - /// - public double Coulombs => As(ElectricChargeUnit.Coulomb); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. - /// - public static ElectricCharge Zero => new ElectricCharge(0, BaseUnit); - - /// - /// Get ElectricCharge from Coulombs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromCoulombs(double coulombs) -#else - public static ElectricCharge FromCoulombs(QuantityValue coulombs) -#endif - { - double value = (double) coulombs; - return new ElectricCharge(value, ElectricChargeUnit.Coulomb); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCharge unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) -#else - public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) -#endif - { - return new ElectricCharge((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCharge)) throw new ArgumentException("Expected type ElectricCharge.", nameof(obj)); - - return CompareTo((ElectricCharge)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCharge other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCharge, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricCharge)) - return false; - - var objQuantity = (ElectricCharge)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricCharge by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricCharge, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricCharge other, ElectricCharge maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCharge. - public override int GetHashCode() - { - return new { type = typeof(ElectricCharge), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCharge to another ElectricCharge with the unit representation . - /// - /// A ElectricCharge with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCharge(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeUnit.Coulomb: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeUnit.Coulomb: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCharge Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCharge result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Coulomb - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricChargeUnit ToStringDefaultUnit { get; set; } = ElectricChargeUnit.Coulomb; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricChargeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCharge - /// - public static ElectricCharge MaxValue => new ElectricCharge(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCharge - /// - public static ElectricCharge MinValue => new ElectricCharge(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCharge.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs deleted file mode 100644 index 48c8f01208..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricChargeDensity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, charge density is a measure of the amount of electric charge per unit length, surface area, or volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricChargeDensity : IQuantity -#else - public partial struct ElectricChargeDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricChargeDensity() - { - BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit CoulombPerCubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricChargeDensity(double coulombspercubicmeter) - { - _value = Convert.ToDouble(coulombspercubicmeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricChargeDensity(double numericValue, ElectricChargeDensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit CoulombPerCubicMeter. - /// - /// Value assuming base unit CoulombPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricChargeDensity(long coulombspercubicmeter) : this(Convert.ToDouble(coulombspercubicmeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit CoulombPerCubicMeter. - /// - /// Value assuming base unit CoulombPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricChargeDensity(decimal coulombspercubicmeter) : this(Convert.ToDouble(coulombspercubicmeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricChargeDensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricChargeDensity quantity. - /// - public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricChargeDensity in CoulombsPerCubicMeter. - /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. - /// - public static ElectricChargeDensity Zero => new ElectricChargeDensity(0, BaseUnit); - - /// - /// Get ElectricChargeDensity from CoulombsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) -#else - public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) -#endif - { - double value = (double) coulombspercubicmeter; - return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricChargeDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit fromUnit) -#else - public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) -#endif - { - return new ElectricChargeDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricChargeDensity)) throw new ArgumentException("Expected type ElectricChargeDensity.", nameof(obj)); - - return CompareTo((ElectricChargeDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricChargeDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricChargeDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricChargeDensity)) - return false; - - var objQuantity = (ElectricChargeDensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricChargeDensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricChargeDensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricChargeDensity other, ElectricChargeDensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricChargeDensity. - public override int GetHashCode() - { - return new { type = typeof(ElectricChargeDensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . - /// - /// A ElectricChargeDensity with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricChargeDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricChargeDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeDensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is CoulombPerCubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricChargeDensityUnit ToStringDefaultUnit { get; set; } = ElectricChargeDensityUnit.CoulombPerCubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricChargeDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MaxValue => new ElectricChargeDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MinValue => new ElectricChargeDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricChargeDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs deleted file mode 100644 index c752bc7ba2..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricConductance.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricConductance : IQuantity -#else - public partial struct ElectricConductance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricConductance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Siemens. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricConductance(double siemens) - { - _value = Convert.ToDouble(siemens); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricConductance(double numericValue, ElectricConductanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Siemens. - /// - /// Value assuming base unit Siemens. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricConductance(long siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Siemens. - /// - /// Value assuming base unit Siemens. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricConductance(decimal siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricConductance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricConductance quantity. - /// - public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricConductance in Microsiemens. - /// - public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); - - /// - /// Get ElectricConductance in Millisiemens. - /// - public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); - - /// - /// Get ElectricConductance in Siemens. - /// - public double Siemens => As(ElectricConductanceUnit.Siemens); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricConductance Zero => new ElectricConductance(0, BaseUnit); - - /// - /// Get ElectricConductance from Microsiemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMicrosiemens(double microsiemens) -#else - public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) -#endif - { - double value = (double) microsiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); - } - - /// - /// Get ElectricConductance from Millisiemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMillisiemens(double millisiemens) -#else - public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) -#endif - { - double value = (double) millisiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); - } - - /// - /// Get ElectricConductance from Siemens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromSiemens(double siemens) -#else - public static ElectricConductance FromSiemens(QuantityValue siemens) -#endif - { - double value = (double) siemens; - return new ElectricConductance(value, ElectricConductanceUnit.Siemens); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) -#else - public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) -#endif - { - return new ElectricConductance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricConductance)) throw new ArgumentException("Expected type ElectricConductance.", nameof(obj)); - - return CompareTo((ElectricConductance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricConductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricConductance)) - return false; - - var objQuantity = (ElectricConductance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricConductance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricConductance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricConductance other, ElectricConductance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductance. - public override int GetHashCode() - { - return new { type = typeof(ElectricConductance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductance to another ElectricConductance with the unit representation . - /// - /// A ElectricConductance with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricConductanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricConductanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricConductanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Siemens - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricConductanceUnit ToStringDefaultUnit { get; set; } = ElectricConductanceUnit.Siemens; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricConductanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricConductance - /// - public static ElectricConductance MaxValue => new ElectricConductance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricConductance - /// - public static ElectricConductance MinValue => new ElectricConductance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricConductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs deleted file mode 100644 index 68bcf5d0ab..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricConductivity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricConductivity : IQuantity -#else - public partial struct ElectricConductivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricConductivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit SiemensPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricConductivity(double siemenspermeter) - { - _value = Convert.ToDouble(siemenspermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricConductivity(double numericValue, ElectricConductivityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit SiemensPerMeter. - /// - /// Value assuming base unit SiemensPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricConductivity(long siemenspermeter) : this(Convert.ToDouble(siemenspermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit SiemensPerMeter. - /// - /// Value assuming base unit SiemensPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricConductivity(decimal siemenspermeter) : this(Convert.ToDouble(siemenspermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricConductivity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricConductivity quantity. - /// - public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricConductivity in SiemensPerMeter. - /// - public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. - /// - public static ElectricConductivity Zero => new ElectricConductivity(0, BaseUnit); - - /// - /// Get ElectricConductivity from SiemensPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) -#else - public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) -#endif - { - double value = (double) siemenspermeter; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductivity From(double value, ElectricConductivityUnit fromUnit) -#else - public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) -#endif - { - return new ElectricConductivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricConductivity)) throw new ArgumentException("Expected type ElectricConductivity.", nameof(obj)); - - return CompareTo((ElectricConductivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricConductivity)) - return false; - - var objQuantity = (ElectricConductivity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricConductivity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricConductivity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricConductivity other, ElectricConductivity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductivity. - public override int GetHashCode() - { - return new { type = typeof(ElectricConductivity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . - /// - /// A ElectricConductivity with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricConductivityUnit.SiemensPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductivityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is SiemensPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricConductivityUnit ToStringDefaultUnit { get; set; } = ElectricConductivityUnit.SiemensPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricConductivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricConductivity - /// - public static ElectricConductivity MaxValue => new ElectricConductivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricConductivity - /// - public static ElectricConductivity MinValue => new ElectricConductivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs deleted file mode 100644 index 1313103839..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrent.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrent : IQuantity -#else - public partial struct ElectricCurrent : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrent() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Ampere. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricCurrent(double amperes) - { - _value = Convert.ToDouble(amperes); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrent(double numericValue, ElectricCurrentUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Ampere. - /// - /// Value assuming base unit Ampere. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrent(long amperes) : this(Convert.ToDouble(amperes), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Ampere. - /// - /// Value assuming base unit Ampere. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrent(decimal amperes) : this(Convert.ToDouble(amperes), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrent; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrent quantity. - /// - public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrent in Amperes. - /// - public double Amperes => As(ElectricCurrentUnit.Ampere); - - /// - /// Get ElectricCurrent in Centiamperes. - /// - public double Centiamperes => As(ElectricCurrentUnit.Centiampere); - - /// - /// Get ElectricCurrent in Kiloamperes. - /// - public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); - - /// - /// Get ElectricCurrent in Megaamperes. - /// - public double Megaamperes => As(ElectricCurrentUnit.Megaampere); - - /// - /// Get ElectricCurrent in Microamperes. - /// - public double Microamperes => As(ElectricCurrentUnit.Microampere); - - /// - /// Get ElectricCurrent in Milliamperes. - /// - public double Milliamperes => As(ElectricCurrentUnit.Milliampere); - - /// - /// Get ElectricCurrent in Nanoamperes. - /// - public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); - - /// - /// Get ElectricCurrent in Picoamperes. - /// - public double Picoamperes => As(ElectricCurrentUnit.Picoampere); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. - /// - public static ElectricCurrent Zero => new ElectricCurrent(0, BaseUnit); - - /// - /// Get ElectricCurrent from Amperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromAmperes(double amperes) -#else - public static ElectricCurrent FromAmperes(QuantityValue amperes) -#endif - { - double value = (double) amperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); - } - - /// - /// Get ElectricCurrent from Centiamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromCentiamperes(double centiamperes) -#else - public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) -#endif - { - double value = (double) centiamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); - } - - /// - /// Get ElectricCurrent from Kiloamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromKiloamperes(double kiloamperes) -#else - public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) -#endif - { - double value = (double) kiloamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); - } - - /// - /// Get ElectricCurrent from Megaamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMegaamperes(double megaamperes) -#else - public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) -#endif - { - double value = (double) megaamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); - } - - /// - /// Get ElectricCurrent from Microamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMicroamperes(double microamperes) -#else - public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) -#endif - { - double value = (double) microamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); - } - - /// - /// Get ElectricCurrent from Milliamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMilliamperes(double milliamperes) -#else - public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) -#endif - { - double value = (double) milliamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); - } - - /// - /// Get ElectricCurrent from Nanoamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromNanoamperes(double nanoamperes) -#else - public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) -#endif - { - double value = (double) nanoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); - } - - /// - /// Get ElectricCurrent from Picoamperes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromPicoamperes(double picoamperes) -#else - public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) -#endif - { - double value = (double) picoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrent unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) -#else - public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) -#endif - { - return new ElectricCurrent((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrent)) throw new ArgumentException("Expected type ElectricCurrent.", nameof(obj)); - - return CompareTo((ElectricCurrent)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrent other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrent, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricCurrent)) - return false; - - var objQuantity = (ElectricCurrent)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricCurrent by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricCurrent, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricCurrent other, ElectricCurrent maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrent. - public override int GetHashCode() - { - return new { type = typeof(ElectricCurrent), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . - /// - /// A ElectricCurrent with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrent(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentUnit.Ampere: return _value; - case ElectricCurrentUnit.Centiampere: return (_value) * 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (_value) * 1e3d; - case ElectricCurrentUnit.Megaampere: return (_value) * 1e6d; - case ElectricCurrentUnit.Microampere: return (_value) * 1e-6d; - case ElectricCurrentUnit.Milliampere: return (_value) * 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (_value) * 1e-9d; - case ElectricCurrentUnit.Picoampere: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentUnit.Ampere: return baseUnitValue; - case ElectricCurrentUnit.Centiampere: return (baseUnitValue) / 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (baseUnitValue) / 1e3d; - case ElectricCurrentUnit.Megaampere: return (baseUnitValue) / 1e6d; - case ElectricCurrentUnit.Microampere: return (baseUnitValue) / 1e-6d; - case ElectricCurrentUnit.Milliampere: return (baseUnitValue) / 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (baseUnitValue) / 1e-9d; - case ElectricCurrentUnit.Picoampere: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrent Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Ampere - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricCurrentUnit ToStringDefaultUnit { get; set; } = ElectricCurrentUnit.Ampere; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrent - /// - public static ElectricCurrent MaxValue => new ElectricCurrent(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrent - /// - public static ElectricCurrent MinValue => new ElectricCurrent(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrent.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs deleted file mode 100644 index 068d588b5e..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrentDensity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, current density is the electric current per unit area of cross section. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrentDensity : IQuantity -#else - public partial struct ElectricCurrentDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrentDensity() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit AmperePerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricCurrentDensity(double amperespersquaremeter) - { - _value = Convert.ToDouble(amperespersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrentDensity(double numericValue, ElectricCurrentDensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit AmperePerSquareMeter. - /// - /// Value assuming base unit AmperePerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrentDensity(long amperespersquaremeter) : this(Convert.ToDouble(amperespersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit AmperePerSquareMeter. - /// - /// Value assuming base unit AmperePerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrentDensity(decimal amperespersquaremeter) : this(Convert.ToDouble(amperespersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrentDensity quantity. - /// - public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrentDensity in AmperesPerSquareMeter. - /// - public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. - /// - public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(0, BaseUnit); - - /// - /// Get ElectricCurrentDensity from AmperesPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) -#else - public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) -#endif - { - double value = (double) amperespersquaremeter; - return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUnit fromUnit) -#else - public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) -#endif - { - return new ElectricCurrentDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrentDensity)) throw new ArgumentException("Expected type ElectricCurrentDensity.", nameof(obj)); - - return CompareTo((ElectricCurrentDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrentDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricCurrentDensity)) - return false; - - var objQuantity = (ElectricCurrentDensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricCurrentDensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricCurrentDensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricCurrentDensity other, ElectricCurrentDensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentDensity. - public override int GetHashCode() - { - return new { type = typeof(ElectricCurrentDensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . - /// - /// A ElectricCurrentDensity with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentDensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is AmperePerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricCurrentDensityUnit ToStringDefaultUnit { get; set; } = ElectricCurrentDensityUnit.AmperePerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MaxValue => new ElectricCurrentDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MinValue => new ElectricCurrentDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrentDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs deleted file mode 100644 index 1880db6d86..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricCurrentGradient.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, the current gradient describes how the current changes in time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricCurrentGradient : IQuantity -#else - public partial struct ElectricCurrentGradient : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentGradientUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricCurrentGradient() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit AmperePerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricCurrentGradient(double amperespersecond) - { - _value = Convert.ToDouble(amperespersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricCurrentGradient(double numericValue, ElectricCurrentGradientUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit AmperePerSecond. - /// - /// Value assuming base unit AmperePerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrentGradient(long amperespersecond) : this(Convert.ToDouble(amperespersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit AmperePerSecond. - /// - /// Value assuming base unit AmperePerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricCurrentGradient(decimal amperespersecond) : this(Convert.ToDouble(amperespersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricCurrentGradient quantity. - /// - public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); - - /// - /// Get ElectricCurrentGradient in AmperesPerSecond. - /// - public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. - /// - public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(0, BaseUnit); - - /// - /// Get ElectricCurrentGradient from AmperesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) -#else - public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) -#endif - { - double value = (double) amperespersecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentGradient unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentGradient From(double value, ElectricCurrentGradientUnit fromUnit) -#else - public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) -#endif - { - return new ElectricCurrentGradient((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentGradientUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricCurrentGradient)) throw new ArgumentException("Expected type ElectricCurrentGradient.", nameof(obj)); - - return CompareTo((ElectricCurrentGradient)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricCurrentGradient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentGradient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricCurrentGradient)) - return false; - - var objQuantity = (ElectricCurrentGradient)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricCurrentGradient by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricCurrentGradient, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricCurrentGradient other, ElectricCurrentGradient maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentGradient. - public override int GetHashCode() - { - return new { type = typeof(ElectricCurrentGradient), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . - /// - /// A ElectricCurrentGradient with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentGradient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentGradientUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentGradient Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentGradientUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is AmperePerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricCurrentGradientUnit ToStringDefaultUnit { get; set; } = ElectricCurrentGradientUnit.AmperePerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricCurrentGradientUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MaxValue => new ElectricCurrentGradient(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MinValue => new ElectricCurrentGradient(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricCurrentGradient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs deleted file mode 100644 index e6df7eee3b..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricField.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricField : IQuantity -#else - public partial struct ElectricField : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricFieldUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricField() - { - BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit VoltPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricField(double voltspermeter) - { - _value = Convert.ToDouble(voltspermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricField(double numericValue, ElectricFieldUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltPerMeter. - /// - /// Value assuming base unit VoltPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricField(long voltspermeter) : this(Convert.ToDouble(voltspermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltPerMeter. - /// - /// Value assuming base unit VoltPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricField(decimal voltspermeter) : this(Convert.ToDouble(voltspermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricField; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricField quantity. - /// - public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); - - /// - /// Get ElectricField in VoltsPerMeter. - /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. - /// - public static ElectricField Zero => new ElectricField(0, BaseUnit); - - /// - /// Get ElectricField from VoltsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricField FromVoltsPerMeter(double voltspermeter) -#else - public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) -#endif - { - double value = (double) voltspermeter; - return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricField unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricField From(double value, ElectricFieldUnit fromUnit) -#else - public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) -#endif - { - return new ElectricField((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricField)) throw new ArgumentException("Expected type ElectricField.", nameof(obj)); - - return CompareTo((ElectricField)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricField)) - return false; - - var objQuantity = (ElectricField)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricField by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricField, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricField other, ElectricField maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricField. - public override int GetHashCode() - { - return new { type = typeof(ElectricField), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricField to another ElectricField with the unit representation . - /// - /// A ElectricField with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricFieldUnit.VoltPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricFieldUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricField Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricField result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricFieldUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricFieldUnit ToStringDefaultUnit { get; set; } = ElectricFieldUnit.VoltPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricFieldUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricField - /// - public static ElectricField MaxValue => new ElectricField(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricField - /// - public static ElectricField MinValue => new ElectricField(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricField.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs deleted file mode 100644 index 06827b5895..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricInductance.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Inductance is a property of an electrical conductor which opposes a change in current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricInductance : IQuantity -#else - public partial struct ElectricInductance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricInductanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricInductance() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Henry. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricInductance(double henries) - { - _value = Convert.ToDouble(henries); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricInductance(double numericValue, ElectricInductanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Henry. - /// - /// Value assuming base unit Henry. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricInductance(long henries) : this(Convert.ToDouble(henries), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Henry. - /// - /// Value assuming base unit Henry. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricInductance(decimal henries) : this(Convert.ToDouble(henries), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricInductance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricInductance quantity. - /// - public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricInductance in Henries. - /// - public double Henries => As(ElectricInductanceUnit.Henry); - - /// - /// Get ElectricInductance in Microhenries. - /// - public double Microhenries => As(ElectricInductanceUnit.Microhenry); - - /// - /// Get ElectricInductance in Millihenries. - /// - public double Millihenries => As(ElectricInductanceUnit.Millihenry); - - /// - /// Get ElectricInductance in Nanohenries. - /// - public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Henry. - /// - public static ElectricInductance Zero => new ElectricInductance(0, BaseUnit); - - /// - /// Get ElectricInductance from Henries. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromHenries(double henries) -#else - public static ElectricInductance FromHenries(QuantityValue henries) -#endif - { - double value = (double) henries; - return new ElectricInductance(value, ElectricInductanceUnit.Henry); - } - - /// - /// Get ElectricInductance from Microhenries. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromMicrohenries(double microhenries) -#else - public static ElectricInductance FromMicrohenries(QuantityValue microhenries) -#endif - { - double value = (double) microhenries; - return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); - } - - /// - /// Get ElectricInductance from Millihenries. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromMillihenries(double millihenries) -#else - public static ElectricInductance FromMillihenries(QuantityValue millihenries) -#endif - { - double value = (double) millihenries; - return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); - } - - /// - /// Get ElectricInductance from Nanohenries. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromNanohenries(double nanohenries) -#else - public static ElectricInductance FromNanohenries(QuantityValue nanohenries) -#endif - { - 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. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricInductance From(double value, ElectricInductanceUnit fromUnit) -#else - public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) -#endif - { - return new ElectricInductance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricInductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricInductance)) throw new ArgumentException("Expected type ElectricInductance.", nameof(obj)); - - return CompareTo((ElectricInductance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricInductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricInductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricInductance)) - return false; - - var objQuantity = (ElectricInductance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricInductance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricInductance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricInductance other, ElectricInductance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricInductance. - public override int GetHashCode() - { - return new { type = typeof(ElectricInductance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricInductance to another ElectricInductance with the unit representation . - /// - /// A ElectricInductance with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricInductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricInductanceUnit.Henry: return _value; - 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 Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricInductance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricInductance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricInductanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Henry - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricInductanceUnit ToStringDefaultUnit { get; set; } = ElectricInductanceUnit.Henry; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricInductanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricInductance - /// - public static ElectricInductance MaxValue => new ElectricInductance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricInductance - /// - public static ElectricInductance MinValue => new ElectricInductance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricInductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs deleted file mode 100644 index 147102a30b..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotential.Common.g.cs +++ /dev/null @@ -1,574 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotential : IQuantity -#else - public partial struct ElectricPotential : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotential() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Volt. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricPotential(double volts) - { - _value = Convert.ToDouble(volts); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotential(double numericValue, ElectricPotentialUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Volt. - /// - /// Value assuming base unit Volt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotential(long volts) : this(Convert.ToDouble(volts), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Volt. - /// - /// Value assuming base unit Volt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotential(decimal volts) : this(Convert.ToDouble(volts), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotential; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotential quantity. - /// - public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotential in Kilovolts. - /// - public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); - - /// - /// Get ElectricPotential in Megavolts. - /// - public double Megavolts => As(ElectricPotentialUnit.Megavolt); - - /// - /// Get ElectricPotential in Microvolts. - /// - public double Microvolts => As(ElectricPotentialUnit.Microvolt); - - /// - /// Get ElectricPotential in Millivolts. - /// - public double Millivolts => As(ElectricPotentialUnit.Millivolt); - - /// - /// Get ElectricPotential in Volts. - /// - public double Volts => As(ElectricPotentialUnit.Volt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Volt. - /// - public static ElectricPotential Zero => new ElectricPotential(0, BaseUnit); - - /// - /// Get ElectricPotential from Kilovolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromKilovolts(double kilovolts) -#else - public static ElectricPotential FromKilovolts(QuantityValue kilovolts) -#endif - { - double value = (double) kilovolts; - return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); - } - - /// - /// Get ElectricPotential from Megavolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMegavolts(double megavolts) -#else - public static ElectricPotential FromMegavolts(QuantityValue megavolts) -#endif - { - double value = (double) megavolts; - return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); - } - - /// - /// Get ElectricPotential from Microvolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMicrovolts(double microvolts) -#else - public static ElectricPotential FromMicrovolts(QuantityValue microvolts) -#endif - { - double value = (double) microvolts; - return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); - } - - /// - /// Get ElectricPotential from Millivolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMillivolts(double millivolts) -#else - public static ElectricPotential FromMillivolts(QuantityValue millivolts) -#endif - { - double value = (double) millivolts; - return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); - } - - /// - /// Get ElectricPotential from Volts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromVolts(double volts) -#else - public static ElectricPotential FromVolts(QuantityValue volts) -#endif - { - double value = (double) volts; - return new ElectricPotential(value, ElectricPotentialUnit.Volt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotential unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) -#else - public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) -#endif - { - return new ElectricPotential((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotential)) throw new ArgumentException("Expected type ElectricPotential.", nameof(obj)); - - return CompareTo((ElectricPotential)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotential other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotential, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricPotential)) - return false; - - var objQuantity = (ElectricPotential)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricPotential by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricPotential, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricPotential other, ElectricPotential maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotential. - public override int GetHashCode() - { - return new { type = typeof(ElectricPotential), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotential to another ElectricPotential with the unit representation . - /// - /// A ElectricPotential with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotential(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialUnit.Kilovolt: return (_value) * 1e3d; - case ElectricPotentialUnit.Megavolt: return (_value) * 1e6d; - case ElectricPotentialUnit.Microvolt: return (_value) * 1e-6d; - case ElectricPotentialUnit.Millivolt: return (_value) * 1e-3d; - case ElectricPotentialUnit.Volt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialUnit.Kilovolt: return (baseUnitValue) / 1e3d; - case ElectricPotentialUnit.Megavolt: return (baseUnitValue) / 1e6d; - case ElectricPotentialUnit.Microvolt: return (baseUnitValue) / 1e-6d; - case ElectricPotentialUnit.Millivolt: return (baseUnitValue) / 1e-3d; - case ElectricPotentialUnit.Volt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotential Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotential result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Volt - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricPotentialUnit ToStringDefaultUnit { get; set; } = ElectricPotentialUnit.Volt; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotential - /// - public static ElectricPotential MaxValue => new ElectricPotential(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotential - /// - public static ElectricPotential MinValue => new ElectricPotential(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotential.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs deleted file mode 100644 index 3a0da333ad..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotentialAc.Common.g.cs +++ /dev/null @@ -1,573 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Alternating Current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotentialAc : IQuantity -#else - public partial struct ElectricPotentialAc : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialAcUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotentialAc() - { - } - - /// - /// Creates the quantity with the given value in the base unit VoltAc. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricPotentialAc(double voltsac) - { - _value = Convert.ToDouble(voltsac); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltAc. - /// - /// Value assuming base unit VoltAc. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotentialAc(long voltsac) : this(Convert.ToDouble(voltsac), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltAc. - /// - /// Value assuming base unit VoltAc. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotentialAc(decimal voltsac) : this(Convert.ToDouble(voltsac), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotentialAc; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotentialAc quantity. - /// - public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotentialAc in KilovoltsAc. - /// - public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); - - /// - /// Get ElectricPotentialAc in MegavoltsAc. - /// - public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); - - /// - /// Get ElectricPotentialAc in MicrovoltsAc. - /// - public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); - - /// - /// Get ElectricPotentialAc in MillivoltsAc. - /// - public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); - - /// - /// Get ElectricPotentialAc in VoltsAc. - /// - public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. - /// - public static ElectricPotentialAc Zero => new ElectricPotentialAc(0, BaseUnit); - - /// - /// Get ElectricPotentialAc from KilovoltsAc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) -#else - public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) -#endif - { - double value = (double) kilovoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); - } - - /// - /// Get ElectricPotentialAc from MegavoltsAc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) -#else - public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) -#endif - { - double value = (double) megavoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); - } - - /// - /// Get ElectricPotentialAc from MicrovoltsAc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) -#else - public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) -#endif - { - double value = (double) microvoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); - } - - /// - /// Get ElectricPotentialAc from MillivoltsAc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) -#else - public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) -#endif - { - double value = (double) millivoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); - } - - /// - /// Get ElectricPotentialAc from VoltsAc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromVoltsAc(double voltsac) -#else - public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) -#endif - { - double value = (double) voltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialAc unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fromUnit) -#else - public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) -#endif - { - return new ElectricPotentialAc((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialAcUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotentialAc)) throw new ArgumentException("Expected type ElectricPotentialAc.", nameof(obj)); - - return CompareTo((ElectricPotentialAc)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotentialAc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialAc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricPotentialAc)) - return false; - - var objQuantity = (ElectricPotentialAc)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricPotentialAc by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricPotentialAc, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricPotentialAc other, ElectricPotentialAc maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialAc. - public override int GetHashCode() - { - return new { type = typeof(ElectricPotentialAc), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialAcUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . - /// - /// A ElectricPotentialAc with the specified unit. - public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialAc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialAcUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialAc Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialAcUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltAc - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricPotentialAcUnit ToStringDefaultUnit { get; set; } = ElectricPotentialAcUnit.VoltAc; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialAcUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MaxValue => new ElectricPotentialAc(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MinValue => new ElectricPotentialAc(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotentialAc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs deleted file mode 100644 index ad022b884c..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricPotentialDc.Common.g.cs +++ /dev/null @@ -1,573 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Direct Current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricPotentialDc : IQuantity -#else - public partial struct ElectricPotentialDc : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialDcUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricPotentialDc() - { - } - - /// - /// Creates the quantity with the given value in the base unit VoltDc. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricPotentialDc(double voltsdc) - { - _value = Convert.ToDouble(voltsdc); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricPotentialDc(double numericValue, ElectricPotentialDcUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltDc. - /// - /// Value assuming base unit VoltDc. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotentialDc(long voltsdc) : this(Convert.ToDouble(voltsdc), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltDc. - /// - /// Value assuming base unit VoltDc. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricPotentialDc(decimal voltsdc) : this(Convert.ToDouble(voltsdc), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricPotentialDc; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricPotentialDc quantity. - /// - public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); - - /// - /// Get ElectricPotentialDc in KilovoltsDc. - /// - public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); - - /// - /// Get ElectricPotentialDc in MegavoltsDc. - /// - public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); - - /// - /// Get ElectricPotentialDc in MicrovoltsDc. - /// - public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); - - /// - /// Get ElectricPotentialDc in MillivoltsDc. - /// - public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); - - /// - /// Get ElectricPotentialDc in VoltsDc. - /// - public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. - /// - public static ElectricPotentialDc Zero => new ElectricPotentialDc(0, BaseUnit); - - /// - /// Get ElectricPotentialDc from KilovoltsDc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) -#else - public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) -#endif - { - double value = (double) kilovoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); - } - - /// - /// Get ElectricPotentialDc from MegavoltsDc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) -#else - public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) -#endif - { - double value = (double) megavoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); - } - - /// - /// Get ElectricPotentialDc from MicrovoltsDc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) -#else - public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) -#endif - { - double value = (double) microvoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); - } - - /// - /// Get ElectricPotentialDc from MillivoltsDc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) -#else - public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) -#endif - { - double value = (double) millivoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); - } - - /// - /// Get ElectricPotentialDc from VoltsDc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromVoltsDc(double voltsdc) -#else - public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) -#endif - { - double value = (double) voltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialDc unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fromUnit) -#else - public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) -#endif - { - return new ElectricPotentialDc((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialDcUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricPotentialDc)) throw new ArgumentException("Expected type ElectricPotentialDc.", nameof(obj)); - - return CompareTo((ElectricPotentialDc)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricPotentialDc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialDc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricPotentialDc)) - return false; - - var objQuantity = (ElectricPotentialDc)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricPotentialDc by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricPotentialDc, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricPotentialDc other, ElectricPotentialDc maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialDc. - public override int GetHashCode() - { - return new { type = typeof(ElectricPotentialDc), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialDcUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . - /// - /// A ElectricPotentialDc with the specified unit. - public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialDc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (_value) * 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (_value) * 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (_value) * 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (_value) * 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialDcUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (baseUnitValue) / 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (baseUnitValue) / 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialDc Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialDcUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltDc - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricPotentialDcUnit ToStringDefaultUnit { get; set; } = ElectricPotentialDcUnit.VoltDc; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricPotentialDcUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MaxValue => new ElectricPotentialDc(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MinValue => new ElectricPotentialDc(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricPotentialDc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs deleted file mode 100644 index c11fbc7cda..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricResistance.Common.g.cs +++ /dev/null @@ -1,574 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricResistance : IQuantity -#else - public partial struct ElectricResistance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricResistance() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Ohm. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricResistance(double ohms) - { - _value = Convert.ToDouble(ohms); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricResistance(double numericValue, ElectricResistanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Ohm. - /// - /// Value assuming base unit Ohm. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricResistance(long ohms) : this(Convert.ToDouble(ohms), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Ohm. - /// - /// Value assuming base unit Ohm. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricResistance(decimal ohms) : this(Convert.ToDouble(ohms), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricResistance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricResistance quantity. - /// - public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); - - /// - /// Get ElectricResistance in Gigaohms. - /// - public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); - - /// - /// Get ElectricResistance in Kiloohms. - /// - public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); - - /// - /// Get ElectricResistance in Megaohms. - /// - public double Megaohms => As(ElectricResistanceUnit.Megaohm); - - /// - /// Get ElectricResistance in Milliohms. - /// - public double Milliohms => As(ElectricResistanceUnit.Milliohm); - - /// - /// Get ElectricResistance in Ohms. - /// - public double Ohms => As(ElectricResistanceUnit.Ohm); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. - /// - public static ElectricResistance Zero => new ElectricResistance(0, BaseUnit); - - /// - /// Get ElectricResistance from Gigaohms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromGigaohms(double gigaohms) -#else - public static ElectricResistance FromGigaohms(QuantityValue gigaohms) -#endif - { - double value = (double) gigaohms; - return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); - } - - /// - /// Get ElectricResistance from Kiloohms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromKiloohms(double kiloohms) -#else - public static ElectricResistance FromKiloohms(QuantityValue kiloohms) -#endif - { - double value = (double) kiloohms; - return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); - } - - /// - /// Get ElectricResistance from Megaohms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMegaohms(double megaohms) -#else - public static ElectricResistance FromMegaohms(QuantityValue megaohms) -#endif - { - double value = (double) megaohms; - return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); - } - - /// - /// Get ElectricResistance from Milliohms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMilliohms(double milliohms) -#else - public static ElectricResistance FromMilliohms(QuantityValue milliohms) -#endif - { - double value = (double) milliohms; - return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); - } - - /// - /// Get ElectricResistance from Ohms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromOhms(double ohms) -#else - public static ElectricResistance FromOhms(QuantityValue ohms) -#endif - { - double value = (double) ohms; - return new ElectricResistance(value, ElectricResistanceUnit.Ohm); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) -#else - public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) -#endif - { - return new ElectricResistance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricResistance)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj)); - - return CompareTo((ElectricResistance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricResistance)) - return false; - - var objQuantity = (ElectricResistance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricResistance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricResistance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricResistance other, ElectricResistance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistance. - public override int GetHashCode() - { - return new { type = typeof(ElectricResistance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistance to another ElectricResistance with the unit representation . - /// - /// A ElectricResistance with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricResistanceUnit.Gigaohm: return (_value) * 1e9d; - case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; - case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; - case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; - case ElectricResistanceUnit.Ohm: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistanceUnit.Gigaohm: return (baseUnitValue) / 1e9d; - case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; - case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; - case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; - case ElectricResistanceUnit.Ohm: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Ohm - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricResistanceUnit ToStringDefaultUnit { get; set; } = ElectricResistanceUnit.Ohm; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricResistanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricResistance - /// - public static ElectricResistance MaxValue => new ElectricResistance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricResistance - /// - public static ElectricResistance MinValue => new ElectricResistance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs b/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs deleted file mode 100644 index 87b6d9e513..0000000000 --- a/Common/GeneratedCode/Quantities/ElectricResistivity.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ElectricResistivity : IQuantity -#else - public partial struct ElectricResistivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ElectricResistivity() - { - BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit OhmMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ElectricResistivity(double ohmmeters) - { - _value = Convert.ToDouble(ohmmeters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ElectricResistivity(double numericValue, ElectricResistivityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit OhmMeter. - /// - /// Value assuming base unit OhmMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricResistivity(long ohmmeters) : this(Convert.ToDouble(ohmmeters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit OhmMeter. - /// - /// Value assuming base unit OhmMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ElectricResistivity(decimal ohmmeters) : this(Convert.ToDouble(ohmmeters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ElectricResistivity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ElectricResistivity quantity. - /// - public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); - - /// - /// Get ElectricResistivity in MicroohmMeters. - /// - public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); - - /// - /// Get ElectricResistivity in MilliohmMeters. - /// - public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); - - /// - /// Get ElectricResistivity in NanoohmMeters. - /// - public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); - - /// - /// Get ElectricResistivity in OhmMeters. - /// - public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. - /// - public static ElectricResistivity Zero => new ElectricResistivity(0, BaseUnit); - - /// - /// Get ElectricResistivity from MicroohmMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMicroohmMeters(double microohmmeters) -#else - public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) -#endif - { - double value = (double) microohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); - } - - /// - /// Get ElectricResistivity from MilliohmMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) -#else - public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) -#endif - { - double value = (double) milliohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); - } - - /// - /// Get ElectricResistivity from NanoohmMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) -#else - public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) -#endif - { - double value = (double) nanoohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); - } - - /// - /// Get ElectricResistivity from OhmMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromOhmMeters(double ohmmeters) -#else - public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) -#endif - { - double value = (double) ohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistivity From(double value, ElectricResistivityUnit fromUnit) -#else - public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) -#endif - { - return new ElectricResistivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ElectricResistivity)) throw new ArgumentException("Expected type ElectricResistivity.", nameof(obj)); - - return CompareTo((ElectricResistivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ElectricResistivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ElectricResistivity)) - return false; - - var objQuantity = (ElectricResistivity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ElectricResistivity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ElectricResistivity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ElectricResistivity other, ElectricResistivity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistivity. - public override int GetHashCode() - { - return new { type = typeof(ElectricResistivity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . - /// - /// A ElectricResistivity with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; - case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; - case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; - case ElectricResistivityUnit.OhmMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; - case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; - case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; - case ElectricResistivityUnit.OhmMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistivityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is OhmMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ElectricResistivityUnit ToStringDefaultUnit { get; set; } = ElectricResistivityUnit.OhmMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ElectricResistivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ElectricResistivity - /// - public static ElectricResistivity MaxValue => new ElectricResistivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ElectricResistivity - /// - public static ElectricResistivity MinValue => new ElectricResistivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ElectricResistivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Energy.Common.g.cs b/Common/GeneratedCode/Quantities/Energy.Common.g.cs deleted file mode 100644 index 5d6a49f4b2..0000000000 --- a/Common/GeneratedCode/Quantities/Energy.Common.g.cs +++ /dev/null @@ -1,931 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Energy : IQuantity -#else - public partial struct Energy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Energy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Joule. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Energy(double joules) - { - _value = Convert.ToDouble(joules); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Energy(double numericValue, EnergyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Joule. - /// - /// Value assuming base unit Joule. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Energy(long joules) : this(Convert.ToDouble(joules), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Joule. - /// - /// Value assuming base unit Joule. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Energy(decimal joules) : this(Convert.ToDouble(joules), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Energy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static EnergyUnit BaseUnit => EnergyUnit.Joule; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Energy quantity. - /// - public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); - - /// - /// Get Energy in BritishThermalUnits. - /// - public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); - - /// - /// Get Energy in Calories. - /// - public double Calories => As(EnergyUnit.Calorie); - - /// - /// Get Energy in DecathermsEc. - /// - public double DecathermsEc => As(EnergyUnit.DecathermEc); - - /// - /// Get Energy in DecathermsImperial. - /// - public double DecathermsImperial => As(EnergyUnit.DecathermImperial); - - /// - /// Get Energy in DecathermsUs. - /// - public double DecathermsUs => As(EnergyUnit.DecathermUs); - - /// - /// Get Energy in ElectronVolts. - /// - public double ElectronVolts => As(EnergyUnit.ElectronVolt); - - /// - /// Get Energy in Ergs. - /// - public double Ergs => As(EnergyUnit.Erg); - - /// - /// Get Energy in FootPounds. - /// - public double FootPounds => As(EnergyUnit.FootPound); - - /// - /// Get Energy in GigabritishThermalUnits. - /// - public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); - - /// - /// Get Energy in GigawattHours. - /// - public double GigawattHours => As(EnergyUnit.GigawattHour); - - /// - /// Get Energy in Joules. - /// - public double Joules => As(EnergyUnit.Joule); - - /// - /// Get Energy in KilobritishThermalUnits. - /// - public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); - - /// - /// Get Energy in Kilocalories. - /// - public double Kilocalories => As(EnergyUnit.Kilocalorie); - - /// - /// Get Energy in Kilojoules. - /// - public double Kilojoules => As(EnergyUnit.Kilojoule); - - /// - /// Get Energy in KilowattHours. - /// - public double KilowattHours => As(EnergyUnit.KilowattHour); - - /// - /// Get Energy in MegabritishThermalUnits. - /// - public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); - - /// - /// Get Energy in Megajoules. - /// - public double Megajoules => As(EnergyUnit.Megajoule); - - /// - /// Get Energy in MegawattHours. - /// - public double MegawattHours => As(EnergyUnit.MegawattHour); - - /// - /// Get Energy in ThermsEc. - /// - public double ThermsEc => As(EnergyUnit.ThermEc); - - /// - /// Get Energy in ThermsImperial. - /// - public double ThermsImperial => As(EnergyUnit.ThermImperial); - - /// - /// Get Energy in ThermsUs. - /// - public double ThermsUs => As(EnergyUnit.ThermUs); - - /// - /// Get Energy in WattHours. - /// - public double WattHours => As(EnergyUnit.WattHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Joule. - /// - public static Energy Zero => new Energy(0, BaseUnit); - - /// - /// Get Energy from BritishThermalUnits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromBritishThermalUnits(double britishthermalunits) -#else - public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) -#endif - { - double value = (double) britishthermalunits; - return new Energy(value, EnergyUnit.BritishThermalUnit); - } - - /// - /// Get Energy from Calories. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromCalories(double calories) -#else - public static Energy FromCalories(QuantityValue calories) -#endif - { - double value = (double) calories; - return new Energy(value, EnergyUnit.Calorie); - } - - /// - /// Get Energy from DecathermsEc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsEc(double decathermsec) -#else - public static Energy FromDecathermsEc(QuantityValue decathermsec) -#endif - { - double value = (double) decathermsec; - return new Energy(value, EnergyUnit.DecathermEc); - } - - /// - /// Get Energy from DecathermsImperial. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsImperial(double decathermsimperial) -#else - public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) -#endif - { - double value = (double) decathermsimperial; - return new Energy(value, EnergyUnit.DecathermImperial); - } - - /// - /// Get Energy from DecathermsUs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsUs(double decathermsus) -#else - public static Energy FromDecathermsUs(QuantityValue decathermsus) -#endif - { - double value = (double) decathermsus; - return new Energy(value, EnergyUnit.DecathermUs); - } - - /// - /// Get Energy from ElectronVolts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromElectronVolts(double electronvolts) -#else - public static Energy FromElectronVolts(QuantityValue electronvolts) -#endif - { - double value = (double) electronvolts; - return new Energy(value, EnergyUnit.ElectronVolt); - } - - /// - /// Get Energy from Ergs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromErgs(double ergs) -#else - public static Energy FromErgs(QuantityValue ergs) -#endif - { - double value = (double) ergs; - return new Energy(value, EnergyUnit.Erg); - } - - /// - /// Get Energy from FootPounds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromFootPounds(double footpounds) -#else - public static Energy FromFootPounds(QuantityValue footpounds) -#endif - { - double value = (double) footpounds; - return new Energy(value, EnergyUnit.FootPound); - } - - /// - /// Get Energy from GigabritishThermalUnits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) -#else - public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) -#endif - { - double value = (double) gigabritishthermalunits; - return new Energy(value, EnergyUnit.GigabritishThermalUnit); - } - - /// - /// Get Energy from GigawattHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigawattHours(double gigawatthours) -#else - public static Energy FromGigawattHours(QuantityValue gigawatthours) -#endif - { - double value = (double) gigawatthours; - return new Energy(value, EnergyUnit.GigawattHour); - } - - /// - /// Get Energy from Joules. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromJoules(double joules) -#else - public static Energy FromJoules(QuantityValue joules) -#endif - { - double value = (double) joules; - return new Energy(value, EnergyUnit.Joule); - } - - /// - /// Get Energy from KilobritishThermalUnits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) -#else - public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) -#endif - { - double value = (double) kilobritishthermalunits; - return new Energy(value, EnergyUnit.KilobritishThermalUnit); - } - - /// - /// Get Energy from Kilocalories. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilocalories(double kilocalories) -#else - public static Energy FromKilocalories(QuantityValue kilocalories) -#endif - { - double value = (double) kilocalories; - return new Energy(value, EnergyUnit.Kilocalorie); - } - - /// - /// Get Energy from Kilojoules. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilojoules(double kilojoules) -#else - public static Energy FromKilojoules(QuantityValue kilojoules) -#endif - { - double value = (double) kilojoules; - return new Energy(value, EnergyUnit.Kilojoule); - } - - /// - /// Get Energy from KilowattHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilowattHours(double kilowatthours) -#else - public static Energy FromKilowattHours(QuantityValue kilowatthours) -#endif - { - double value = (double) kilowatthours; - return new Energy(value, EnergyUnit.KilowattHour); - } - - /// - /// Get Energy from MegabritishThermalUnits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) -#else - public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) -#endif - { - double value = (double) megabritishthermalunits; - return new Energy(value, EnergyUnit.MegabritishThermalUnit); - } - - /// - /// Get Energy from Megajoules. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegajoules(double megajoules) -#else - public static Energy FromMegajoules(QuantityValue megajoules) -#endif - { - double value = (double) megajoules; - return new Energy(value, EnergyUnit.Megajoule); - } - - /// - /// Get Energy from MegawattHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegawattHours(double megawatthours) -#else - public static Energy FromMegawattHours(QuantityValue megawatthours) -#endif - { - double value = (double) megawatthours; - return new Energy(value, EnergyUnit.MegawattHour); - } - - /// - /// Get Energy from ThermsEc. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsEc(double thermsec) -#else - public static Energy FromThermsEc(QuantityValue thermsec) -#endif - { - double value = (double) thermsec; - return new Energy(value, EnergyUnit.ThermEc); - } - - /// - /// Get Energy from ThermsImperial. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsImperial(double thermsimperial) -#else - public static Energy FromThermsImperial(QuantityValue thermsimperial) -#endif - { - double value = (double) thermsimperial; - return new Energy(value, EnergyUnit.ThermImperial); - } - - /// - /// Get Energy from ThermsUs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsUs(double thermsus) -#else - public static Energy FromThermsUs(QuantityValue thermsus) -#endif - { - double value = (double) thermsus; - return new Energy(value, EnergyUnit.ThermUs); - } - - /// - /// Get Energy from WattHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromWattHours(double watthours) -#else - public static Energy FromWattHours(QuantityValue watthours) -#endif - { - double value = (double) watthours; - return new Energy(value, EnergyUnit.WattHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Energy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Energy From(double value, EnergyUnit fromUnit) -#else - public static Energy From(QuantityValue value, EnergyUnit fromUnit) -#endif - { - return new Energy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Energy)) throw new ArgumentException("Expected type Energy.", nameof(obj)); - - return CompareTo((Energy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Energy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Energy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Energy)) - return false; - - var objQuantity = (Energy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Energy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Energy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Energy other, Energy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Energy. - public override int GetHashCode() - { - return new { type = typeof(Energy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Energy to another Energy with the unit representation . - /// - /// A Energy with the specified unit. - public Energy ToUnit(EnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Energy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; - case EnergyUnit.Calorie: return _value*4.184; - case EnergyUnit.DecathermEc: return (_value*1.05505585262e8) * 1e1d; - case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e8) * 1e1d; - case EnergyUnit.DecathermUs: return (_value*1.054804e8) * 1e1d; - case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; - case EnergyUnit.Erg: return _value*1e-7; - case EnergyUnit.FootPound: return _value*1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; - case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; - case EnergyUnit.Joule: return _value; - case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; - case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; - case EnergyUnit.Kilojoule: return (_value) * 1e3d; - case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; - case EnergyUnit.Megajoule: return (_value) * 1e6d; - case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; - case EnergyUnit.ThermEc: return _value*1.05505585262e8; - case EnergyUnit.ThermImperial: return _value*1.05505585257348e8; - case EnergyUnit.ThermUs: return _value*1.054804e8; - case EnergyUnit.WattHour: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; - case EnergyUnit.Calorie: return baseUnitValue/4.184; - case EnergyUnit.DecathermEc: return (baseUnitValue/1.05505585262e8) / 1e1d; - case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e8) / 1e1d; - case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e8) / 1e1d; - case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; - case EnergyUnit.Erg: return baseUnitValue/1e-7; - case EnergyUnit.FootPound: return baseUnitValue/1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; - case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; - case EnergyUnit.Joule: return baseUnitValue; - case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; - case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; - case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; - case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; - case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; - case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; - case EnergyUnit.ThermEc: return baseUnitValue/1.05505585262e8; - case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e8; - case EnergyUnit.ThermUs: return baseUnitValue/1.054804e8; - case EnergyUnit.WattHour: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Energy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Energy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EnergyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Joule - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static EnergyUnit ToStringDefaultUnit { get; set; } = EnergyUnit.Joule; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(EnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Energy - /// - public static Energy MaxValue => new Energy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Energy - /// - public static Energy MinValue => new Energy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Energy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Energy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Entropy.Common.g.cs b/Common/GeneratedCode/Quantities/Entropy.Common.g.cs deleted file mode 100644 index 8917943faa..0000000000 --- a/Common/GeneratedCode/Quantities/Entropy.Common.g.cs +++ /dev/null @@ -1,616 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Entropy : IQuantity -#else - public partial struct Entropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Entropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Entropy(double joulesperkelvin) - { - _value = Convert.ToDouble(joulesperkelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Entropy(double numericValue, EntropyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKelvin. - /// - /// Value assuming base unit JoulePerKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Entropy(long joulesperkelvin) : this(Convert.ToDouble(joulesperkelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKelvin. - /// - /// Value assuming base unit JoulePerKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Entropy(decimal joulesperkelvin) : this(Convert.ToDouble(joulesperkelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Entropy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Entropy quantity. - /// - public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); - - /// - /// Get Entropy in CaloriesPerKelvin. - /// - public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); - - /// - /// Get Entropy in JoulesPerDegreeCelsius. - /// - public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); - - /// - /// Get Entropy in JoulesPerKelvin. - /// - public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); - - /// - /// Get Entropy in KilocaloriesPerKelvin. - /// - public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); - - /// - /// Get Entropy in KilojoulesPerDegreeCelsius. - /// - public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); - - /// - /// Get Entropy in KilojoulesPerKelvin. - /// - public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); - - /// - /// Get Entropy in MegajoulesPerKelvin. - /// - public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. - /// - public static Entropy Zero => new Entropy(0, BaseUnit); - - /// - /// Get Entropy from CaloriesPerKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) -#else - public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) -#endif - { - double value = (double) caloriesperkelvin; - return new Entropy(value, EntropyUnit.CaloriePerKelvin); - } - - /// - /// Get Entropy from JoulesPerDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) -#else - public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) -#endif - { - double value = (double) joulesperdegreecelsius; - return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); - } - - /// - /// Get Entropy from JoulesPerKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerKelvin(double joulesperkelvin) -#else - public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) -#endif - { - double value = (double) joulesperkelvin; - return new Entropy(value, EntropyUnit.JoulePerKelvin); - } - - /// - /// Get Entropy from KilocaloriesPerKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) -#else - public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) -#endif - { - double value = (double) kilocaloriesperkelvin; - return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); - } - - /// - /// Get Entropy from KilojoulesPerDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) -#else - public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) -#endif - { - double value = (double) kilojoulesperdegreecelsius; - return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); - } - - /// - /// Get Entropy from KilojoulesPerKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) -#else - public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) -#endif - { - double value = (double) kilojoulesperkelvin; - return new Entropy(value, EntropyUnit.KilojoulePerKelvin); - } - - /// - /// Get Entropy from MegajoulesPerKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) -#else - public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) -#endif - { - double value = (double) megajoulesperkelvin; - return new Entropy(value, EntropyUnit.MegajoulePerKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Entropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Entropy From(double value, EntropyUnit fromUnit) -#else - public static Entropy From(QuantityValue value, EntropyUnit fromUnit) -#endif - { - return new Entropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Entropy)) throw new ArgumentException("Expected type Entropy.", nameof(obj)); - - return CompareTo((Entropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Entropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Entropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Entropy)) - return false; - - var objQuantity = (Entropy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Entropy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Entropy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Entropy other, Entropy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Entropy. - public override int GetHashCode() - { - return new { type = typeof(Entropy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Entropy to another Entropy with the unit representation . - /// - /// A Entropy with the specified unit. - public Entropy ToUnit(EntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Entropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case EntropyUnit.CaloriePerKelvin: return _value*4.184; - case EntropyUnit.JoulePerDegreeCelsius: return _value; - case EntropyUnit.JoulePerKelvin: return _value; - case EntropyUnit.KilocaloriePerKelvin: return (_value*4.184) * 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (_value) * 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (_value) * 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EntropyUnit.CaloriePerKelvin: return baseUnitValue/4.184; - case EntropyUnit.JoulePerDegreeCelsius: return baseUnitValue; - case EntropyUnit.JoulePerKelvin: return baseUnitValue; - case EntropyUnit.KilocaloriePerKelvin: return (baseUnitValue/4.184) / 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (baseUnitValue) / 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (baseUnitValue) / 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Entropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Entropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EntropyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static EntropyUnit ToStringDefaultUnit { get; set; } = EntropyUnit.JoulePerKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(EntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Entropy - /// - public static Entropy MaxValue => new Entropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Entropy - /// - public static Entropy MinValue => new Entropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Entropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Entropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Flow.Common.g.cs b/Common/GeneratedCode/Quantities/Flow.Common.g.cs deleted file mode 100644 index c09adf53bc..0000000000 --- a/Common/GeneratedCode/Quantities/Flow.Common.g.cs +++ /dev/null @@ -1,1010 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // ReSharper disable once PartialTypeWithSinglePart - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow 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. -#if WINDOWS_UWP - public sealed partial class Flow : IQuantity -#else - public partial struct Flow : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly FlowUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public FlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Flow() - { - BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit CubicMeterPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Flow(double cubicmeterspersecond) - { - _value = Convert.ToDouble(cubicmeterspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Flow(double numericValue, FlowUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. - /// - /// Value assuming base unit CubicMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Flow(long cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. - /// - /// Value assuming base unit CubicMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Flow(decimal cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Flow; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static FlowUnit BaseUnit => FlowUnit.CubicMeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Flow quantity. - /// - public static FlowUnit[] Units { get; } = Enum.GetValues(typeof(FlowUnit)).Cast().Except(new FlowUnit[]{ FlowUnit.Undefined }).ToArray(); - - /// - /// Get Flow in CentilitersPerMinute. - /// - public double CentilitersPerMinute => As(FlowUnit.CentilitersPerMinute); - - /// - /// Get Flow in CubicDecimetersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicDecimetersPerMinute => As(FlowUnit.CubicDecimeterPerMinute); - - /// - /// Get Flow in CubicFeetPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerHour => As(FlowUnit.CubicFootPerHour); - - /// - /// Get Flow in CubicFeetPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerMinute => As(FlowUnit.CubicFootPerMinute); - - /// - /// Get Flow in CubicFeetPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerSecond => As(FlowUnit.CubicFootPerSecond); - - /// - /// Get Flow in CubicMetersPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerHour => As(FlowUnit.CubicMeterPerHour); - - /// - /// Get Flow in CubicMetersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerMinute => As(FlowUnit.CubicMeterPerMinute); - - /// - /// Get Flow in CubicMetersPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerSecond => As(FlowUnit.CubicMeterPerSecond); - - /// - /// Get Flow in CubicYardsPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerHour => As(FlowUnit.CubicYardPerHour); - - /// - /// Get Flow in CubicYardsPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerMinute => As(FlowUnit.CubicYardPerMinute); - - /// - /// Get Flow in CubicYardsPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerSecond => As(FlowUnit.CubicYardPerSecond); - - /// - /// Get Flow in DecilitersPerMinute. - /// - public double DecilitersPerMinute => As(FlowUnit.DecilitersPerMinute); - - /// - /// Get Flow in KilolitersPerMinute. - /// - public double KilolitersPerMinute => As(FlowUnit.KilolitersPerMinute); - - /// - /// Get Flow in LitersPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerHour => As(FlowUnit.LitersPerHour); - - /// - /// Get Flow in LitersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerMinute => As(FlowUnit.LitersPerMinute); - - /// - /// Get Flow in LitersPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerSecond => As(FlowUnit.LitersPerSecond); - - /// - /// Get Flow in MicrolitersPerMinute. - /// - public double MicrolitersPerMinute => As(FlowUnit.MicrolitersPerMinute); - - /// - /// Get Flow in MillilitersPerMinute. - /// - public double MillilitersPerMinute => As(FlowUnit.MillilitersPerMinute); - - /// - /// Get Flow in MillionUsGallonsPerDay. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double MillionUsGallonsPerDay => As(FlowUnit.MillionUsGallonsPerDay); - - /// - /// Get Flow in NanolitersPerMinute. - /// - public double NanolitersPerMinute => As(FlowUnit.NanolitersPerMinute); - - /// - /// Get Flow in OilBarrelsPerDay. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double OilBarrelsPerDay => As(FlowUnit.OilBarrelsPerDay); - - /// - /// Get Flow in UsGallonsPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerHour => As(FlowUnit.UsGallonsPerHour); - - /// - /// Get Flow in UsGallonsPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerMinute => As(FlowUnit.UsGallonsPerMinute); - - /// - /// Get Flow in UsGallonsPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerSecond => As(FlowUnit.UsGallonsPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - public static Flow Zero => new Flow(0, BaseUnit); - - /// - /// Get Flow from CentilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCentilitersPerMinute(double centilitersperminute) -#else - public static Flow FromCentilitersPerMinute(QuantityValue centilitersperminute) -#endif - { - double value = (double) centilitersperminute; - return new Flow(value, FlowUnit.CentilitersPerMinute); - } - - /// - /// Get Flow from CubicDecimetersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) -#else - public static Flow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) -#endif - { - double value = (double) cubicdecimetersperminute; - return new Flow(value, FlowUnit.CubicDecimeterPerMinute); - } - - /// - /// Get Flow from CubicFeetPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicFeetPerHour(double cubicfeetperhour) -#else - public static Flow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) -#endif - { - double value = (double) cubicfeetperhour; - return new Flow(value, FlowUnit.CubicFootPerHour); - } - - /// - /// Get Flow from CubicFeetPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicFeetPerMinute(double cubicfeetperminute) -#else - public static Flow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) -#endif - { - double value = (double) cubicfeetperminute; - return new Flow(value, FlowUnit.CubicFootPerMinute); - } - - /// - /// Get Flow from CubicFeetPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicFeetPerSecond(double cubicfeetpersecond) -#else - public static Flow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) -#endif - { - double value = (double) cubicfeetpersecond; - return new Flow(value, FlowUnit.CubicFootPerSecond); - } - - /// - /// Get Flow from CubicMetersPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicMetersPerHour(double cubicmetersperhour) -#else - public static Flow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) -#endif - { - double value = (double) cubicmetersperhour; - return new Flow(value, FlowUnit.CubicMeterPerHour); - } - - /// - /// Get Flow from CubicMetersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicMetersPerMinute(double cubicmetersperminute) -#else - public static Flow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) -#endif - { - double value = (double) cubicmetersperminute; - return new Flow(value, FlowUnit.CubicMeterPerMinute); - } - - /// - /// Get Flow from CubicMetersPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicMetersPerSecond(double cubicmeterspersecond) -#else - public static Flow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) -#endif - { - double value = (double) cubicmeterspersecond; - return new Flow(value, FlowUnit.CubicMeterPerSecond); - } - - /// - /// Get Flow from CubicYardsPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicYardsPerHour(double cubicyardsperhour) -#else - public static Flow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) -#endif - { - double value = (double) cubicyardsperhour; - return new Flow(value, FlowUnit.CubicYardPerHour); - } - - /// - /// Get Flow from CubicYardsPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicYardsPerMinute(double cubicyardsperminute) -#else - public static Flow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) -#endif - { - double value = (double) cubicyardsperminute; - return new Flow(value, FlowUnit.CubicYardPerMinute); - } - - /// - /// Get Flow from CubicYardsPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromCubicYardsPerSecond(double cubicyardspersecond) -#else - public static Flow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) -#endif - { - double value = (double) cubicyardspersecond; - return new Flow(value, FlowUnit.CubicYardPerSecond); - } - - /// - /// Get Flow from DecilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromDecilitersPerMinute(double decilitersperminute) -#else - public static Flow FromDecilitersPerMinute(QuantityValue decilitersperminute) -#endif - { - double value = (double) decilitersperminute; - return new Flow(value, FlowUnit.DecilitersPerMinute); - } - - /// - /// Get Flow from KilolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromKilolitersPerMinute(double kilolitersperminute) -#else - public static Flow FromKilolitersPerMinute(QuantityValue kilolitersperminute) -#endif - { - double value = (double) kilolitersperminute; - return new Flow(value, FlowUnit.KilolitersPerMinute); - } - - /// - /// Get Flow from LitersPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromLitersPerHour(double litersperhour) -#else - public static Flow FromLitersPerHour(QuantityValue litersperhour) -#endif - { - double value = (double) litersperhour; - return new Flow(value, FlowUnit.LitersPerHour); - } - - /// - /// Get Flow from LitersPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromLitersPerMinute(double litersperminute) -#else - public static Flow FromLitersPerMinute(QuantityValue litersperminute) -#endif - { - double value = (double) litersperminute; - return new Flow(value, FlowUnit.LitersPerMinute); - } - - /// - /// Get Flow from LitersPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromLitersPerSecond(double literspersecond) -#else - public static Flow FromLitersPerSecond(QuantityValue literspersecond) -#endif - { - double value = (double) literspersecond; - return new Flow(value, FlowUnit.LitersPerSecond); - } - - /// - /// Get Flow from MicrolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromMicrolitersPerMinute(double microlitersperminute) -#else - public static Flow FromMicrolitersPerMinute(QuantityValue microlitersperminute) -#endif - { - double value = (double) microlitersperminute; - return new Flow(value, FlowUnit.MicrolitersPerMinute); - } - - /// - /// Get Flow from MillilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromMillilitersPerMinute(double millilitersperminute) -#else - public static Flow FromMillilitersPerMinute(QuantityValue millilitersperminute) -#endif - { - double value = (double) millilitersperminute; - return new Flow(value, FlowUnit.MillilitersPerMinute); - } - - /// - /// Get Flow from MillionUsGallonsPerDay. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromMillionUsGallonsPerDay(double millionusgallonsperday) -#else - public static Flow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) -#endif - { - double value = (double) millionusgallonsperday; - return new Flow(value, FlowUnit.MillionUsGallonsPerDay); - } - - /// - /// Get Flow from NanolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromNanolitersPerMinute(double nanolitersperminute) -#else - public static Flow FromNanolitersPerMinute(QuantityValue nanolitersperminute) -#endif - { - double value = (double) nanolitersperminute; - return new Flow(value, FlowUnit.NanolitersPerMinute); - } - - /// - /// Get Flow from OilBarrelsPerDay. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromOilBarrelsPerDay(double oilbarrelsperday) -#else - public static Flow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) -#endif - { - double value = (double) oilbarrelsperday; - return new Flow(value, FlowUnit.OilBarrelsPerDay); - } - - /// - /// Get Flow from UsGallonsPerHour. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromUsGallonsPerHour(double usgallonsperhour) -#else - public static Flow FromUsGallonsPerHour(QuantityValue usgallonsperhour) -#endif - { - double value = (double) usgallonsperhour; - return new Flow(value, FlowUnit.UsGallonsPerHour); - } - - /// - /// Get Flow from UsGallonsPerMinute. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromUsGallonsPerMinute(double usgallonsperminute) -#else - public static Flow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) -#endif - { - double value = (double) usgallonsperminute; - return new Flow(value, FlowUnit.UsGallonsPerMinute); - } - - /// - /// Get Flow from UsGallonsPerSecond. - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Flow FromUsGallonsPerSecond(double usgallonspersecond) -#else - public static Flow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) -#endif - { - double value = (double) usgallonspersecond; - return new Flow(value, FlowUnit.UsGallonsPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Flow unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Flow From(double value, FlowUnit fromUnit) -#else - public static Flow From(QuantityValue value, FlowUnit fromUnit) -#endif - { - return new Flow((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Flow)) throw new ArgumentException("Expected type Flow.", nameof(obj)); - - return CompareTo((Flow)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Flow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Flow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Flow)) - return false; - - var objQuantity = (Flow)obj; - return _value.Equals(objQuantity.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Flow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Flow other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Compare equality to another Flow by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Flow, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Flow other, Flow maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Flow. - public override int GetHashCode() - { - return new { type = typeof(Flow), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FlowUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Flow to another Flow with the unit representation . - /// - /// A Flow with the specified unit. - public Flow ToUnit(FlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Flow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case FlowUnit.CentilitersPerMinute: return (_value/60000.00000) * 1e-2d; - case FlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; - case FlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; - case FlowUnit.CubicFootPerMinute: return _value/2118.88000326; - case FlowUnit.CubicFootPerSecond: return _value/35.314666721; - case FlowUnit.CubicMeterPerHour: return _value/3600; - case FlowUnit.CubicMeterPerMinute: return _value/60; - case FlowUnit.CubicMeterPerSecond: return _value; - case FlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; - case FlowUnit.CubicYardPerMinute: return _value*0.0127425809664; - case FlowUnit.CubicYardPerSecond: return _value*0.764554857984; - case FlowUnit.DecilitersPerMinute: return (_value/60000.00000) * 1e-1d; - case FlowUnit.KilolitersPerMinute: return (_value/60000.00000) * 1e3d; - case FlowUnit.LitersPerHour: return _value/3600000.000; - case FlowUnit.LitersPerMinute: return _value/60000.00000; - case FlowUnit.LitersPerSecond: return _value/1000; - case FlowUnit.MicrolitersPerMinute: return (_value/60000.00000) * 1e-6d; - case FlowUnit.MillilitersPerMinute: return (_value/60000.00000) * 1e-3d; - case FlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; - case FlowUnit.NanolitersPerMinute: return (_value/60000.00000) * 1e-9d; - case FlowUnit.OilBarrelsPerDay: return _value*1.8401307283333333333333333333333e-6; - case FlowUnit.UsGallonsPerHour: return _value/951019.38848933424; - case FlowUnit.UsGallonsPerMinute: return _value/15850.323141489; - case FlowUnit.UsGallonsPerSecond: return _value/264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(FlowUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case FlowUnit.CentilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; - case FlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; - case FlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; - case FlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; - case FlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; - case FlowUnit.CubicMeterPerHour: return baseUnitValue*3600; - case FlowUnit.CubicMeterPerMinute: return baseUnitValue*60; - case FlowUnit.CubicMeterPerSecond: return baseUnitValue; - case FlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; - case FlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; - case FlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; - case FlowUnit.DecilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; - case FlowUnit.KilolitersPerMinute: return (baseUnitValue*60000.00000) / 1e3d; - case FlowUnit.LitersPerHour: return baseUnitValue*3600000.000; - case FlowUnit.LitersPerMinute: return baseUnitValue*60000.00000; - case FlowUnit.LitersPerSecond: return baseUnitValue*1000; - case FlowUnit.MicrolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; - case FlowUnit.MillilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; - case FlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; - case FlowUnit.NanolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; - case FlowUnit.OilBarrelsPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; - case FlowUnit.UsGallonsPerHour: return baseUnitValue*951019.38848933424; - case FlowUnit.UsGallonsPerMinute: return baseUnitValue*15850.323141489; - case FlowUnit.UsGallonsPerSecond: return baseUnitValue*264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Flow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Flow result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FlowUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is CubicMeterPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static FlowUnit ToStringDefaultUnit { get; set; } = FlowUnit.CubicMeterPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(FlowUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Flow - /// - public static Flow MaxValue => new Flow(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Flow - /// - public static Flow MinValue => new Flow(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Flow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Flow.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Force.Common.g.cs b/Common/GeneratedCode/Quantities/Force.Common.g.cs deleted file mode 100644 index 76c1e98ce2..0000000000 --- a/Common/GeneratedCode/Quantities/Force.Common.g.cs +++ /dev/null @@ -1,742 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Force : IQuantity -#else - public partial struct Force : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Force() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Newton. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Force(double newtons) - { - _value = Convert.ToDouble(newtons); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Force(double numericValue, ForceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Newton. - /// - /// Value assuming base unit Newton. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Force(long newtons) : this(Convert.ToDouble(newtons), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Newton. - /// - /// Value assuming base unit Newton. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Force(decimal newtons) : this(Convert.ToDouble(newtons), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Force; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ForceUnit BaseUnit => ForceUnit.Newton; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Force quantity. - /// - public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); - - /// - /// Get Force in Decanewtons. - /// - public double Decanewtons => As(ForceUnit.Decanewton); - - /// - /// Get Force in Dyne. - /// - public double Dyne => As(ForceUnit.Dyn); - - /// - /// Get Force in KilogramsForce. - /// - public double KilogramsForce => As(ForceUnit.KilogramForce); - - /// - /// Get Force in Kilonewtons. - /// - public double Kilonewtons => As(ForceUnit.Kilonewton); - - /// - /// Get Force in KiloPonds. - /// - public double KiloPonds => As(ForceUnit.KiloPond); - - /// - /// Get Force in Meganewtons. - /// - public double Meganewtons => As(ForceUnit.Meganewton); - - /// - /// Get Force in Micronewtons. - /// - public double Micronewtons => As(ForceUnit.Micronewton); - - /// - /// Get Force in Millinewtons. - /// - public double Millinewtons => As(ForceUnit.Millinewton); - - /// - /// Get Force in Newtons. - /// - public double Newtons => As(ForceUnit.Newton); - - /// - /// Get Force in OunceForce. - /// - public double OunceForce => As(ForceUnit.OunceForce); - - /// - /// Get Force in Poundals. - /// - public double Poundals => As(ForceUnit.Poundal); - - /// - /// Get Force in PoundsForce. - /// - public double PoundsForce => As(ForceUnit.PoundForce); - - /// - /// Get Force in TonnesForce. - /// - public double TonnesForce => As(ForceUnit.TonneForce); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Newton. - /// - public static Force Zero => new Force(0, BaseUnit); - - /// - /// Get Force from Decanewtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDecanewtons(double decanewtons) -#else - public static Force FromDecanewtons(QuantityValue decanewtons) -#endif - { - double value = (double) decanewtons; - return new Force(value, ForceUnit.Decanewton); - } - - /// - /// Get Force from Dyne. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDyne(double dyne) -#else - public static Force FromDyne(QuantityValue dyne) -#endif - { - double value = (double) dyne; - return new Force(value, ForceUnit.Dyn); - } - - /// - /// Get Force from KilogramsForce. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilogramsForce(double kilogramsforce) -#else - public static Force FromKilogramsForce(QuantityValue kilogramsforce) -#endif - { - double value = (double) kilogramsforce; - return new Force(value, ForceUnit.KilogramForce); - } - - /// - /// Get Force from Kilonewtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilonewtons(double kilonewtons) -#else - public static Force FromKilonewtons(QuantityValue kilonewtons) -#endif - { - double value = (double) kilonewtons; - return new Force(value, ForceUnit.Kilonewton); - } - - /// - /// Get Force from KiloPonds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKiloPonds(double kiloponds) -#else - public static Force FromKiloPonds(QuantityValue kiloponds) -#endif - { - double value = (double) kiloponds; - return new Force(value, ForceUnit.KiloPond); - } - - /// - /// Get Force from Meganewtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMeganewtons(double meganewtons) -#else - public static Force FromMeganewtons(QuantityValue meganewtons) -#endif - { - double value = (double) meganewtons; - return new Force(value, ForceUnit.Meganewton); - } - - /// - /// Get Force from Micronewtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMicronewtons(double micronewtons) -#else - public static Force FromMicronewtons(QuantityValue micronewtons) -#endif - { - double value = (double) micronewtons; - return new Force(value, ForceUnit.Micronewton); - } - - /// - /// Get Force from Millinewtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMillinewtons(double millinewtons) -#else - public static Force FromMillinewtons(QuantityValue millinewtons) -#endif - { - double value = (double) millinewtons; - return new Force(value, ForceUnit.Millinewton); - } - - /// - /// Get Force from Newtons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromNewtons(double newtons) -#else - public static Force FromNewtons(QuantityValue newtons) -#endif - { - double value = (double) newtons; - return new Force(value, ForceUnit.Newton); - } - - /// - /// Get Force from OunceForce. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromOunceForce(double ounceforce) -#else - public static Force FromOunceForce(QuantityValue ounceforce) -#endif - { - double value = (double) ounceforce; - return new Force(value, ForceUnit.OunceForce); - } - - /// - /// Get Force from Poundals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundals(double poundals) -#else - public static Force FromPoundals(QuantityValue poundals) -#endif - { - double value = (double) poundals; - return new Force(value, ForceUnit.Poundal); - } - - /// - /// Get Force from PoundsForce. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundsForce(double poundsforce) -#else - public static Force FromPoundsForce(QuantityValue poundsforce) -#endif - { - double value = (double) poundsforce; - return new Force(value, ForceUnit.PoundForce); - } - - /// - /// Get Force from TonnesForce. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromTonnesForce(double tonnesforce) -#else - public static Force FromTonnesForce(QuantityValue tonnesforce) -#endif - { - double value = (double) tonnesforce; - return new Force(value, ForceUnit.TonneForce); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Force unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Force From(double value, ForceUnit fromUnit) -#else - public static Force From(QuantityValue value, ForceUnit fromUnit) -#endif - { - return new Force((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Force)) throw new ArgumentException("Expected type Force.", nameof(obj)); - - return CompareTo((Force)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Force other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Force, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Force)) - return false; - - var objQuantity = (Force)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Force by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Force, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Force other, Force maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Force. - public override int GetHashCode() - { - return new { type = typeof(Force), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Force to another Force with the unit representation . - /// - /// A Force with the specified unit. - public Force ToUnit(ForceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Force(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForceUnit.Decanewton: return (_value) * 1e1d; - case ForceUnit.Dyn: return _value/1e5; - case ForceUnit.KilogramForce: return _value*9.80665002864; - case ForceUnit.Kilonewton: return (_value) * 1e3d; - case ForceUnit.KiloPond: return _value*9.80665002864; - case ForceUnit.Meganewton: return (_value) * 1e6d; - case ForceUnit.Micronewton: return (_value) * 1e-6d; - case ForceUnit.Millinewton: return (_value) * 1e-3d; - case ForceUnit.Newton: return _value; - case ForceUnit.OunceForce: return _value*2.780138509537812e-1; - case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; - case ForceUnit.TonneForce: return _value*9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; - case ForceUnit.Dyn: return baseUnitValue*1e5; - case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; - case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; - case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; - case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; - case ForceUnit.Micronewton: return (baseUnitValue) / 1e-6d; - case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; - case ForceUnit.Newton: return baseUnitValue; - case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; - case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; - case ForceUnit.TonneForce: return baseUnitValue/9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Force Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Force result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Newton - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ForceUnit ToStringDefaultUnit { get; set; } = ForceUnit.Newton; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Force - /// - public static Force MaxValue => new Force(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Force - /// - public static Force MinValue => new Force(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Force.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Force.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs deleted file mode 100644 index 8e774ffc2f..0000000000 --- a/Common/GeneratedCode/Quantities/ForceChangeRate.Common.g.cs +++ /dev/null @@ -1,700 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ForceChangeRate : IQuantity -#else - public partial struct ForceChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ForceChangeRate() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ForceChangeRate(double newtonspersecond) - { - _value = Convert.ToDouble(newtonspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ForceChangeRate(double numericValue, ForceChangeRateUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerSecond. - /// - /// Value assuming base unit NewtonPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ForceChangeRate(long newtonspersecond) : this(Convert.ToDouble(newtonspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerSecond. - /// - /// Value assuming base unit NewtonPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ForceChangeRate(decimal newtonspersecond) : this(Convert.ToDouble(newtonspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ForceChangeRate; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ForceChangeRate quantity. - /// - public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get ForceChangeRate in CentinewtonsPerSecond. - /// - public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); - - /// - /// Get ForceChangeRate in DecanewtonsPerMinute. - /// - public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); - - /// - /// Get ForceChangeRate in DecanewtonsPerSecond. - /// - public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); - - /// - /// Get ForceChangeRate in DecinewtonsPerSecond. - /// - public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); - - /// - /// Get ForceChangeRate in KilonewtonsPerMinute. - /// - public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); - - /// - /// Get ForceChangeRate in KilonewtonsPerSecond. - /// - public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); - - /// - /// Get ForceChangeRate in MicronewtonsPerSecond. - /// - public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); - - /// - /// Get ForceChangeRate in MillinewtonsPerSecond. - /// - public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); - - /// - /// Get ForceChangeRate in NanonewtonsPerSecond. - /// - public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); - - /// - /// Get ForceChangeRate in NewtonsPerMinute. - /// - public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); - - /// - /// Get ForceChangeRate in NewtonsPerSecond. - /// - public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. - /// - public static ForceChangeRate Zero => new ForceChangeRate(0, BaseUnit); - - /// - /// Get ForceChangeRate from CentinewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) -#else - public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) -#endif - { - double value = (double) centinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from DecanewtonsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) -#else - public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) -#endif - { - double value = (double) decanewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); - } - - /// - /// Get ForceChangeRate from DecanewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) -#else - public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) -#endif - { - double value = (double) decanewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); - } - - /// - /// Get ForceChangeRate from DecinewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) -#else - public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) -#endif - { - double value = (double) decinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from KilonewtonsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) -#else - public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) -#endif - { - double value = (double) kilonewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); - } - - /// - /// Get ForceChangeRate from KilonewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) -#else - public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) -#endif - { - double value = (double) kilonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); - } - - /// - /// Get ForceChangeRate from MicronewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) -#else - public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) -#endif - { - double value = (double) micronewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); - } - - /// - /// Get ForceChangeRate from MillinewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) -#else - public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) -#endif - { - double value = (double) millinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); - } - - /// - /// Get ForceChangeRate from NanonewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) -#else - public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) -#endif - { - double value = (double) nanonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); - } - - /// - /// Get ForceChangeRate from NewtonsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) -#else - public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) -#endif - { - double value = (double) newtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); - } - - /// - /// Get ForceChangeRate from NewtonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) -#else - public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) -#endif - { - double value = (double) newtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForceChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) -#else - public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) -#endif - { - return new ForceChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ForceChangeRate)) throw new ArgumentException("Expected type ForceChangeRate.", nameof(obj)); - - return CompareTo((ForceChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ForceChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForceChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ForceChangeRate)) - return false; - - var objQuantity = (ForceChangeRate)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ForceChangeRate by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ForceChangeRate, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ForceChangeRate other, ForceChangeRate maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForceChangeRate. - public override int GetHashCode() - { - return new { type = typeof(ForceChangeRate), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . - /// - /// A ForceChangeRate with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForceChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return _value/60; - case ForceChangeRateUnit.NewtonPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; - case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForceChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ForceChangeRateUnit ToStringDefaultUnit { get; set; } = ForceChangeRateUnit.NewtonPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForceChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ForceChangeRate - /// - public static ForceChangeRate MaxValue => new ForceChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ForceChangeRate - /// - public static ForceChangeRate MinValue => new ForceChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ForceChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs b/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs deleted file mode 100644 index 729665e35d..0000000000 --- a/Common/GeneratedCode/Quantities/ForcePerLength.Common.g.cs +++ /dev/null @@ -1,658 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The magnitude of force per unit length. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ForcePerLength : IQuantity -#else - public partial struct ForcePerLength : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForcePerLengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ForcePerLength() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ForcePerLength(double newtonspermeter) - { - _value = Convert.ToDouble(newtonspermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ForcePerLength(double numericValue, ForcePerLengthUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerMeter. - /// - /// Value assuming base unit NewtonPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ForcePerLength(long newtonspermeter) : this(Convert.ToDouble(newtonspermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerMeter. - /// - /// Value assuming base unit NewtonPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ForcePerLength(decimal newtonspermeter) : this(Convert.ToDouble(newtonspermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ForcePerLength; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ForcePerLength quantity. - /// - public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); - - /// - /// Get ForcePerLength in CentinewtonsPerMeter. - /// - public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); - - /// - /// Get ForcePerLength in DecinewtonsPerMeter. - /// - public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); - - /// - /// Get ForcePerLength in KilogramsForcePerMeter. - /// - public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); - - /// - /// Get ForcePerLength in KilonewtonsPerMeter. - /// - public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); - - /// - /// Get ForcePerLength in MeganewtonsPerMeter. - /// - public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); - - /// - /// Get ForcePerLength in MicronewtonsPerMeter. - /// - public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); - - /// - /// Get ForcePerLength in MillinewtonsPerMeter. - /// - public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); - - /// - /// Get ForcePerLength in NanonewtonsPerMeter. - /// - public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); - - /// - /// Get ForcePerLength in NewtonsPerMeter. - /// - public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. - /// - public static ForcePerLength Zero => new ForcePerLength(0, BaseUnit); - - /// - /// Get ForcePerLength from CentinewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) -#else - public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) -#endif - { - double value = (double) centinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); - } - - /// - /// Get ForcePerLength from DecinewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) -#else - public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) -#endif - { - double value = (double) decinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); - } - - /// - /// Get ForcePerLength from KilogramsForcePerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) -#else - public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) -#endif - { - double value = (double) kilogramsforcepermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); - } - - /// - /// Get ForcePerLength from KilonewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) -#else - public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) -#endif - { - double value = (double) kilonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); - } - - /// - /// Get ForcePerLength from MeganewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) -#else - public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) -#endif - { - double value = (double) meganewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); - } - - /// - /// Get ForcePerLength from MicronewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) -#else - public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) -#endif - { - double value = (double) micronewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); - } - - /// - /// Get ForcePerLength from MillinewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) -#else - public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) -#endif - { - double value = (double) millinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); - } - - /// - /// Get ForcePerLength from NanonewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) -#else - public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) -#endif - { - double value = (double) nanonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); - } - - /// - /// Get ForcePerLength from NewtonsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) -#else - public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) -#endif - { - double value = (double) newtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForcePerLength unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) -#else - public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) -#endif - { - return new ForcePerLength((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForcePerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ForcePerLength)) throw new ArgumentException("Expected type ForcePerLength.", nameof(obj)); - - return CompareTo((ForcePerLength)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ForcePerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForcePerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ForcePerLength)) - return false; - - var objQuantity = (ForcePerLength)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ForcePerLength by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ForcePerLength, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ForcePerLength other, ForcePerLength maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForcePerLength. - public override int GetHashCode() - { - return new { type = typeof(ForcePerLength), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForcePerLength to another ForcePerLength with the unit representation . - /// - /// A ForcePerLength with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForcePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; - case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; - case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; - case ForcePerLengthUnit.NewtonPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForcePerLengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; - case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; - case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; - case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForcePerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForcePerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForcePerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ForcePerLengthUnit ToStringDefaultUnit { get; set; } = ForcePerLengthUnit.NewtonPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ForcePerLengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ForcePerLength - /// - public static ForcePerLength MaxValue => new ForcePerLength(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ForcePerLength - /// - public static ForcePerLength MinValue => new ForcePerLength(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ForcePerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Frequency.Common.g.cs b/Common/GeneratedCode/Quantities/Frequency.Common.g.cs deleted file mode 100644 index 62044a6ae8..0000000000 --- a/Common/GeneratedCode/Quantities/Frequency.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The number of occurrences of a repeating event per unit time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Frequency : IQuantity -#else - public partial struct Frequency : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly FrequencyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Frequency() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Hertz. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Frequency(double hertz) - { - _value = Convert.ToDouble(hertz); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Frequency(double numericValue, FrequencyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Hertz. - /// - /// Value assuming base unit Hertz. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Frequency(long hertz) : this(Convert.ToDouble(hertz), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Hertz. - /// - /// Value assuming base unit Hertz. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Frequency(decimal hertz) : this(Convert.ToDouble(hertz), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Frequency; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Frequency quantity. - /// - public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); - - /// - /// Get Frequency in CyclesPerHour. - /// - public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); - - /// - /// Get Frequency in CyclesPerMinute. - /// - public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); - - /// - /// Get Frequency in Gigahertz. - /// - public double Gigahertz => As(FrequencyUnit.Gigahertz); - - /// - /// Get Frequency in Hertz. - /// - public double Hertz => As(FrequencyUnit.Hertz); - - /// - /// Get Frequency in Kilohertz. - /// - public double Kilohertz => As(FrequencyUnit.Kilohertz); - - /// - /// Get Frequency in Megahertz. - /// - public double Megahertz => As(FrequencyUnit.Megahertz); - - /// - /// Get Frequency in RadiansPerSecond. - /// - public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); - - /// - /// Get Frequency in Terahertz. - /// - public double Terahertz => As(FrequencyUnit.Terahertz); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. - /// - public static Frequency Zero => new Frequency(0, BaseUnit); - - /// - /// Get Frequency from CyclesPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerHour(double cyclesperhour) -#else - public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) -#endif - { - double value = (double) cyclesperhour; - return new Frequency(value, FrequencyUnit.CyclePerHour); - } - - /// - /// Get Frequency from CyclesPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerMinute(double cyclesperminute) -#else - public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) -#endif - { - double value = (double) cyclesperminute; - return new Frequency(value, FrequencyUnit.CyclePerMinute); - } - - /// - /// Get Frequency from Gigahertz. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromGigahertz(double gigahertz) -#else - public static Frequency FromGigahertz(QuantityValue gigahertz) -#endif - { - double value = (double) gigahertz; - return new Frequency(value, FrequencyUnit.Gigahertz); - } - - /// - /// Get Frequency from Hertz. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromHertz(double hertz) -#else - public static Frequency FromHertz(QuantityValue hertz) -#endif - { - double value = (double) hertz; - return new Frequency(value, FrequencyUnit.Hertz); - } - - /// - /// Get Frequency from Kilohertz. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromKilohertz(double kilohertz) -#else - public static Frequency FromKilohertz(QuantityValue kilohertz) -#endif - { - double value = (double) kilohertz; - return new Frequency(value, FrequencyUnit.Kilohertz); - } - - /// - /// Get Frequency from Megahertz. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromMegahertz(double megahertz) -#else - public static Frequency FromMegahertz(QuantityValue megahertz) -#endif - { - double value = (double) megahertz; - return new Frequency(value, FrequencyUnit.Megahertz); - } - - /// - /// Get Frequency from RadiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromRadiansPerSecond(double radianspersecond) -#else - public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) -#endif - { - double value = (double) radianspersecond; - return new Frequency(value, FrequencyUnit.RadianPerSecond); - } - - /// - /// Get Frequency from Terahertz. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromTerahertz(double terahertz) -#else - public static Frequency FromTerahertz(QuantityValue terahertz) -#endif - { - double value = (double) terahertz; - return new Frequency(value, FrequencyUnit.Terahertz); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Frequency unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Frequency From(double value, FrequencyUnit fromUnit) -#else - public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) -#endif - { - return new Frequency((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FrequencyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Frequency)) throw new ArgumentException("Expected type Frequency.", nameof(obj)); - - return CompareTo((Frequency)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Frequency other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Frequency, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Frequency)) - return false; - - var objQuantity = (Frequency)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Frequency by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Frequency, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Frequency other, Frequency maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Frequency. - public override int GetHashCode() - { - return new { type = typeof(Frequency), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FrequencyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Frequency to another Frequency with the unit representation . - /// - /// A Frequency with the specified unit. - public Frequency ToUnit(FrequencyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Frequency(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case FrequencyUnit.CyclePerHour: return _value/3600; - case FrequencyUnit.CyclePerMinute: return _value/60; - case FrequencyUnit.Gigahertz: return (_value) * 1e9d; - case FrequencyUnit.Hertz: return _value; - case FrequencyUnit.Kilohertz: return (_value) * 1e3d; - case FrequencyUnit.Megahertz: return (_value) * 1e6d; - case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; - case FrequencyUnit.Terahertz: return (_value) * 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(FrequencyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; - case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; - case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; - case FrequencyUnit.Hertz: return baseUnitValue; - case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; - case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; - case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; - case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Frequency Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Frequency result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FrequencyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Hertz - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static FrequencyUnit ToStringDefaultUnit { get; set; } = FrequencyUnit.Hertz; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(FrequencyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Frequency - /// - public static Frequency MaxValue => new Frequency(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Frequency - /// - public static Frequency MinValue => new Frequency(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Frequency.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Frequency.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs b/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs deleted file mode 100644 index 613c5cf201..0000000000 --- a/Common/GeneratedCode/Quantities/HeatFlux.Common.g.cs +++ /dev/null @@ -1,847 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat flux is the flow of energy per unit of area per unit of time - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class HeatFlux : IQuantity -#else - public partial struct HeatFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static HeatFlux() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit WattPerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public HeatFlux(double wattspersquaremeter) - { - _value = Convert.ToDouble(wattspersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - HeatFlux(double numericValue, HeatFluxUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. - /// - /// Value assuming base unit WattPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - HeatFlux(long wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. - /// - /// Value assuming base unit WattPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - HeatFlux(decimal wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.HeatFlux; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the HeatFlux quantity. - /// - public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); - - /// - /// Get HeatFlux in BtusPerHourSquareFoot. - /// - public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); - - /// - /// Get HeatFlux in BtusPerMinuteSquareFoot. - /// - public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); - - /// - /// Get HeatFlux in BtusPerSecondSquareFoot. - /// - public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); - - /// - /// Get HeatFlux in BtusPerSecondSquareInch. - /// - public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); - - /// - /// Get HeatFlux in CaloriesPerSecondSquareCentimeter. - /// - public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); - - /// - /// Get HeatFlux in CentiwattsPerSquareMeter. - /// - public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); - - /// - /// Get HeatFlux in DeciwattsPerSquareMeter. - /// - public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); - - /// - /// Get HeatFlux in KilocaloriesPerHourSquareMeter. - /// - public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); - - /// - /// Get HeatFlux in KilocaloriesPerSecondSquareCentimeter. - /// - public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - - /// - /// Get HeatFlux in KilowattsPerSquareMeter. - /// - public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); - - /// - /// Get HeatFlux in MicrowattsPerSquareMeter. - /// - public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); - - /// - /// Get HeatFlux in MilliwattsPerSquareMeter. - /// - public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); - - /// - /// Get HeatFlux in NanowattsPerSquareMeter. - /// - public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); - - /// - /// Get HeatFlux in PoundsForcePerFootSecond. - /// - public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); - - /// - /// Get HeatFlux in PoundsPerSecondCubed. - /// - public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); - - /// - /// Get HeatFlux in WattsPerSquareFoot. - /// - public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); - - /// - /// Get HeatFlux in WattsPerSquareInch. - /// - public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); - - /// - /// Get HeatFlux in WattsPerSquareMeter. - /// - public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static HeatFlux Zero => new HeatFlux(0, BaseUnit); - - /// - /// Get HeatFlux from BtusPerHourSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerHourSquareFoot(double btusperhoursquarefoot) -#else - public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) -#endif - { - double value = (double) btusperhoursquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerMinuteSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerMinuteSquareFoot(double btusperminutesquarefoot) -#else - public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) -#endif - { - double value = (double) btusperminutesquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerSecondSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareFoot(double btuspersecondsquarefoot) -#else - public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) -#endif - { - double value = (double) btuspersecondsquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); - } - - /// - /// Get HeatFlux from BtusPerSecondSquareInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareInch(double btuspersecondsquareinch) -#else - public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) -#endif - { - double value = (double) btuspersecondsquareinch; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); - } - - /// - /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double caloriespersecondsquarecentimeter) -#else - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) -#endif - { - double value = (double) caloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); - } - - /// - /// Get HeatFlux from CentiwattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCentiwattsPerSquareMeter(double centiwattspersquaremeter) -#else - public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) -#endif - { - double value = (double) centiwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); - } - - /// - /// Get HeatFlux from DeciwattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromDeciwattsPerSquareMeter(double deciwattspersquaremeter) -#else - public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) -#endif - { - double value = (double) deciwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); - } - - /// - /// Get HeatFlux from KilocaloriesPerHourSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerHourSquareMeter(double kilocaloriesperhoursquaremeter) -#else - public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) -#endif - { - double value = (double) kilocaloriesperhoursquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); - } - - /// - /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double kilocaloriespersecondsquarecentimeter) -#else - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) -#endif - { - double value = (double) kilocaloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - } - - /// - /// Get HeatFlux from KilowattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilowattsPerSquareMeter(double kilowattspersquaremeter) -#else - public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) -#endif - { - double value = (double) kilowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); - } - - /// - /// Get HeatFlux from MicrowattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMicrowattsPerSquareMeter(double microwattspersquaremeter) -#else - public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) -#endif - { - double value = (double) microwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); - } - - /// - /// Get HeatFlux from MilliwattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) -#else - public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) -#endif - { - double value = (double) milliwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); - } - - /// - /// Get HeatFlux from NanowattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromNanowattsPerSquareMeter(double nanowattspersquaremeter) -#else - public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) -#endif - { - double value = (double) nanowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); - } - - /// - /// Get HeatFlux from PoundsForcePerFootSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromPoundsForcePerFootSecond(double poundsforceperfootsecond) -#else - public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue poundsforceperfootsecond) -#endif - { - double value = (double) poundsforceperfootsecond; - return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); - } - - /// - /// Get HeatFlux from PoundsPerSecondCubed. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromPoundsPerSecondCubed(double poundspersecondcubed) -#else - public static HeatFlux FromPoundsPerSecondCubed(QuantityValue poundspersecondcubed) -#endif - { - double value = (double) poundspersecondcubed; - return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); - } - - /// - /// Get HeatFlux from WattsPerSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareFoot(double wattspersquarefoot) -#else - public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) -#endif - { - double value = (double) wattspersquarefoot; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); - } - - /// - /// Get HeatFlux from WattsPerSquareInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareInch(double wattspersquareinch) -#else - public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) -#endif - { - double value = (double) wattspersquareinch; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); - } - - /// - /// Get HeatFlux from WattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareMeter(double wattspersquaremeter) -#else - public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) -#endif - { - double value = (double) wattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatFlux From(double value, HeatFluxUnit fromUnit) -#else - public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) -#endif - { - return new HeatFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is HeatFlux)) throw new ArgumentException("Expected type HeatFlux.", nameof(obj)); - - return CompareTo((HeatFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(HeatFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is HeatFlux)) - return false; - - var objQuantity = (HeatFlux)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another HeatFlux by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(HeatFlux, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(HeatFlux other, HeatFlux maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatFlux. - public override int GetHashCode() - { - return new { type = typeof(HeatFlux), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatFlux to another HeatFlux with the unit representation . - /// - /// A HeatFlux with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return _value*3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return _value*1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return _value*1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return _value*1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return _value*4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (_value) * 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (_value) * 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return _value*1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (_value*4.1868e4) * 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case HeatFluxUnit.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 Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatFluxUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is WattPerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static HeatFluxUnit ToStringDefaultUnit { get; set; } = HeatFluxUnit.WattPerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(HeatFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of HeatFlux - /// - public static HeatFlux MaxValue => new HeatFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of HeatFlux - /// - public static HeatFlux MinValue => new HeatFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => HeatFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs b/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs deleted file mode 100644 index 3cba0c1089..0000000000 --- a/Common/GeneratedCode/Quantities/HeatTransferCoefficient.Common.g.cs +++ /dev/null @@ -1,511 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class HeatTransferCoefficient : IQuantity -#else - public partial struct HeatTransferCoefficient : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatTransferCoefficientUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static HeatTransferCoefficient() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit WattPerSquareMeterKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public HeatTransferCoefficient(double wattspersquaremeterkelvin) - { - _value = Convert.ToDouble(wattspersquaremeterkelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - HeatTransferCoefficient(double numericValue, HeatTransferCoefficientUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeterKelvin. - /// - /// Value assuming base unit WattPerSquareMeterKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - HeatTransferCoefficient(long wattspersquaremeterkelvin) : this(Convert.ToDouble(wattspersquaremeterkelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeterKelvin. - /// - /// Value assuming base unit WattPerSquareMeterKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - HeatTransferCoefficient(decimal wattspersquaremeterkelvin) : this(Convert.ToDouble(wattspersquaremeterkelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the HeatTransferCoefficient quantity. - /// - public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); - - /// - /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. - /// - public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - - /// - /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. - /// - public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. - /// - public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(0, BaseUnit); - - /// - /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double wattspersquaremetercelsius) -#else - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) -#endif - { - double value = (double) wattspersquaremetercelsius; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - } - - /// - /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double wattspersquaremeterkelvin) -#else - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) -#endif - { - double value = (double) wattspersquaremeterkelvin; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatTransferCoefficient unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatTransferCoefficient From(double value, HeatTransferCoefficientUnit fromUnit) -#else - public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) -#endif - { - return new HeatTransferCoefficient((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatTransferCoefficientUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is HeatTransferCoefficient)) throw new ArgumentException("Expected type HeatTransferCoefficient.", nameof(obj)); - - return CompareTo((HeatTransferCoefficient)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(HeatTransferCoefficient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatTransferCoefficient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is HeatTransferCoefficient)) - return false; - - var objQuantity = (HeatTransferCoefficient)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another HeatTransferCoefficient by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(HeatTransferCoefficient, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(HeatTransferCoefficient other, HeatTransferCoefficient maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatTransferCoefficient. - public override int GetHashCode() - { - return new { type = typeof(HeatTransferCoefficient), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . - /// - /// A HeatTransferCoefficient with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatTransferCoefficient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return _value; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(HeatTransferCoefficientUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatTransferCoefficient Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatTransferCoefficientUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is WattPerSquareMeterKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static HeatTransferCoefficientUnit ToStringDefaultUnit { get; set; } = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(HeatTransferCoefficientUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MaxValue => new HeatTransferCoefficient(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MinValue => new HeatTransferCoefficient(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => HeatTransferCoefficient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs b/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs deleted file mode 100644 index 6017e87c55..0000000000 --- a/Common/GeneratedCode/Quantities/Illuminance.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Illuminance : IQuantity -#else - public partial struct Illuminance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IlluminanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Illuminance() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given value in the base unit Lux. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Illuminance(double lux) - { - _value = Convert.ToDouble(lux); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Illuminance(double numericValue, IlluminanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Lux. - /// - /// Value assuming base unit Lux. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Illuminance(long lux) : this(Convert.ToDouble(lux), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Lux. - /// - /// Value assuming base unit Lux. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Illuminance(decimal lux) : this(Convert.ToDouble(lux), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Illuminance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Illuminance quantity. - /// - public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); - - /// - /// Get Illuminance in Kilolux. - /// - public double Kilolux => As(IlluminanceUnit.Kilolux); - - /// - /// Get Illuminance in Lux. - /// - public double Lux => As(IlluminanceUnit.Lux); - - /// - /// Get Illuminance in Megalux. - /// - public double Megalux => As(IlluminanceUnit.Megalux); - - /// - /// Get Illuminance in Millilux. - /// - public double Millilux => As(IlluminanceUnit.Millilux); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lux. - /// - public static Illuminance Zero => new Illuminance(0, BaseUnit); - - /// - /// Get Illuminance from Kilolux. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromKilolux(double kilolux) -#else - public static Illuminance FromKilolux(QuantityValue kilolux) -#endif - { - double value = (double) kilolux; - return new Illuminance(value, IlluminanceUnit.Kilolux); - } - - /// - /// Get Illuminance from Lux. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromLux(double lux) -#else - public static Illuminance FromLux(QuantityValue lux) -#endif - { - double value = (double) lux; - return new Illuminance(value, IlluminanceUnit.Lux); - } - - /// - /// Get Illuminance from Megalux. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMegalux(double megalux) -#else - public static Illuminance FromMegalux(QuantityValue megalux) -#endif - { - double value = (double) megalux; - return new Illuminance(value, IlluminanceUnit.Megalux); - } - - /// - /// Get Illuminance from Millilux. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMillilux(double millilux) -#else - public static Illuminance FromMillilux(QuantityValue millilux) -#endif - { - double value = (double) millilux; - return new Illuminance(value, IlluminanceUnit.Millilux); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Illuminance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Illuminance From(double value, IlluminanceUnit fromUnit) -#else - public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) -#endif - { - return new Illuminance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IlluminanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Illuminance)) throw new ArgumentException("Expected type Illuminance.", nameof(obj)); - - return CompareTo((Illuminance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Illuminance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Illuminance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Illuminance)) - return false; - - var objQuantity = (Illuminance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Illuminance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Illuminance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Illuminance other, Illuminance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Illuminance. - public override int GetHashCode() - { - return new { type = typeof(Illuminance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Illuminance to another Illuminance with the unit representation . - /// - /// A Illuminance with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Illuminance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IlluminanceUnit.Kilolux: return (_value) * 1e3d; - case IlluminanceUnit.Lux: return _value; - case IlluminanceUnit.Megalux: return (_value) * 1e6d; - case IlluminanceUnit.Millilux: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IlluminanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IlluminanceUnit.Kilolux: return (baseUnitValue) / 1e3d; - case IlluminanceUnit.Lux: return baseUnitValue; - case IlluminanceUnit.Megalux: return (baseUnitValue) / 1e6d; - case IlluminanceUnit.Millilux: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Illuminance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Illuminance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IlluminanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Lux - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static IlluminanceUnit ToStringDefaultUnit { get; set; } = IlluminanceUnit.Lux; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IlluminanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Illuminance - /// - public static Illuminance MaxValue => new Illuminance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Illuminance - /// - public static Illuminance MinValue => new Illuminance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Illuminance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Illuminance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Information.Common.g.cs b/Common/GeneratedCode/Quantities/Information.Common.g.cs deleted file mode 100644 index 3051e9b23a..0000000000 --- a/Common/GeneratedCode/Quantities/Information.Common.g.cs +++ /dev/null @@ -1,1013 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Information : IQuantity -#else - public partial struct Information : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly InformationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Information() - { - } - - /// - /// Creates the quantity with the given value in the base unit Bit. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Information(double bits) - { - _value = Convert.ToDecimal(bits); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Information(decimal numericValue, InformationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Bit. - /// - /// Value assuming base unit Bit. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Information(long bits) : this(Convert.ToDecimal(bits), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Bit. - /// - /// Value assuming base unit Bit. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Information(decimal bits) : this(Convert.ToDecimal(bits), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Information; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static InformationUnit BaseUnit => InformationUnit.Bit; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Information quantity. - /// - public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); - - /// - /// Get Information in Bits. - /// - public double Bits => As(InformationUnit.Bit); - - /// - /// Get Information in Bytes. - /// - public double Bytes => As(InformationUnit.Byte); - - /// - /// Get Information in Exabits. - /// - public double Exabits => As(InformationUnit.Exabit); - - /// - /// Get Information in Exabytes. - /// - public double Exabytes => As(InformationUnit.Exabyte); - - /// - /// Get Information in Exbibits. - /// - public double Exbibits => As(InformationUnit.Exbibit); - - /// - /// Get Information in Exbibytes. - /// - public double Exbibytes => As(InformationUnit.Exbibyte); - - /// - /// Get Information in Gibibits. - /// - public double Gibibits => As(InformationUnit.Gibibit); - - /// - /// Get Information in Gibibytes. - /// - public double Gibibytes => As(InformationUnit.Gibibyte); - - /// - /// Get Information in Gigabits. - /// - public double Gigabits => As(InformationUnit.Gigabit); - - /// - /// Get Information in Gigabytes. - /// - public double Gigabytes => As(InformationUnit.Gigabyte); - - /// - /// Get Information in Kibibits. - /// - public double Kibibits => As(InformationUnit.Kibibit); - - /// - /// Get Information in Kibibytes. - /// - public double Kibibytes => As(InformationUnit.Kibibyte); - - /// - /// Get Information in Kilobits. - /// - public double Kilobits => As(InformationUnit.Kilobit); - - /// - /// Get Information in Kilobytes. - /// - public double Kilobytes => As(InformationUnit.Kilobyte); - - /// - /// Get Information in Mebibits. - /// - public double Mebibits => As(InformationUnit.Mebibit); - - /// - /// Get Information in Mebibytes. - /// - public double Mebibytes => As(InformationUnit.Mebibyte); - - /// - /// Get Information in Megabits. - /// - public double Megabits => As(InformationUnit.Megabit); - - /// - /// Get Information in Megabytes. - /// - public double Megabytes => As(InformationUnit.Megabyte); - - /// - /// Get Information in Pebibits. - /// - public double Pebibits => As(InformationUnit.Pebibit); - - /// - /// Get Information in Pebibytes. - /// - public double Pebibytes => As(InformationUnit.Pebibyte); - - /// - /// Get Information in Petabits. - /// - public double Petabits => As(InformationUnit.Petabit); - - /// - /// Get Information in Petabytes. - /// - public double Petabytes => As(InformationUnit.Petabyte); - - /// - /// Get Information in Tebibits. - /// - public double Tebibits => As(InformationUnit.Tebibit); - - /// - /// Get Information in Tebibytes. - /// - public double Tebibytes => As(InformationUnit.Tebibyte); - - /// - /// Get Information in Terabits. - /// - public double Terabits => As(InformationUnit.Terabit); - - /// - /// Get Information in Terabytes. - /// - public double Terabytes => As(InformationUnit.Terabyte); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Bit. - /// - public static Information Zero => new Information(0, BaseUnit); - - /// - /// Get Information from Bits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBits(double bits) -#else - public static Information FromBits(QuantityValue bits) -#endif - { - decimal value = (decimal) bits; - return new Information(value, InformationUnit.Bit); - } - - /// - /// Get Information from Bytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBytes(double bytes) -#else - public static Information FromBytes(QuantityValue bytes) -#endif - { - decimal value = (decimal) bytes; - return new Information(value, InformationUnit.Byte); - } - - /// - /// Get Information from Exabits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabits(double exabits) -#else - public static Information FromExabits(QuantityValue exabits) -#endif - { - decimal value = (decimal) exabits; - return new Information(value, InformationUnit.Exabit); - } - - /// - /// Get Information from Exabytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabytes(double exabytes) -#else - public static Information FromExabytes(QuantityValue exabytes) -#endif - { - decimal value = (decimal) exabytes; - return new Information(value, InformationUnit.Exabyte); - } - - /// - /// Get Information from Exbibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibits(double exbibits) -#else - public static Information FromExbibits(QuantityValue exbibits) -#endif - { - decimal value = (decimal) exbibits; - return new Information(value, InformationUnit.Exbibit); - } - - /// - /// Get Information from Exbibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibytes(double exbibytes) -#else - public static Information FromExbibytes(QuantityValue exbibytes) -#endif - { - decimal value = (decimal) exbibytes; - return new Information(value, InformationUnit.Exbibyte); - } - - /// - /// Get Information from Gibibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibits(double gibibits) -#else - public static Information FromGibibits(QuantityValue gibibits) -#endif - { - decimal value = (decimal) gibibits; - return new Information(value, InformationUnit.Gibibit); - } - - /// - /// Get Information from Gibibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibytes(double gibibytes) -#else - public static Information FromGibibytes(QuantityValue gibibytes) -#endif - { - decimal value = (decimal) gibibytes; - return new Information(value, InformationUnit.Gibibyte); - } - - /// - /// Get Information from Gigabits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabits(double gigabits) -#else - public static Information FromGigabits(QuantityValue gigabits) -#endif - { - decimal value = (decimal) gigabits; - return new Information(value, InformationUnit.Gigabit); - } - - /// - /// Get Information from Gigabytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabytes(double gigabytes) -#else - public static Information FromGigabytes(QuantityValue gigabytes) -#endif - { - decimal value = (decimal) gigabytes; - return new Information(value, InformationUnit.Gigabyte); - } - - /// - /// Get Information from Kibibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibits(double kibibits) -#else - public static Information FromKibibits(QuantityValue kibibits) -#endif - { - decimal value = (decimal) kibibits; - return new Information(value, InformationUnit.Kibibit); - } - - /// - /// Get Information from Kibibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibytes(double kibibytes) -#else - public static Information FromKibibytes(QuantityValue kibibytes) -#endif - { - decimal value = (decimal) kibibytes; - return new Information(value, InformationUnit.Kibibyte); - } - - /// - /// Get Information from Kilobits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobits(double kilobits) -#else - public static Information FromKilobits(QuantityValue kilobits) -#endif - { - decimal value = (decimal) kilobits; - return new Information(value, InformationUnit.Kilobit); - } - - /// - /// Get Information from Kilobytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobytes(double kilobytes) -#else - public static Information FromKilobytes(QuantityValue kilobytes) -#endif - { - decimal value = (decimal) kilobytes; - return new Information(value, InformationUnit.Kilobyte); - } - - /// - /// Get Information from Mebibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibits(double mebibits) -#else - public static Information FromMebibits(QuantityValue mebibits) -#endif - { - decimal value = (decimal) mebibits; - return new Information(value, InformationUnit.Mebibit); - } - - /// - /// Get Information from Mebibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibytes(double mebibytes) -#else - public static Information FromMebibytes(QuantityValue mebibytes) -#endif - { - decimal value = (decimal) mebibytes; - return new Information(value, InformationUnit.Mebibyte); - } - - /// - /// Get Information from Megabits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabits(double megabits) -#else - public static Information FromMegabits(QuantityValue megabits) -#endif - { - decimal value = (decimal) megabits; - return new Information(value, InformationUnit.Megabit); - } - - /// - /// Get Information from Megabytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabytes(double megabytes) -#else - public static Information FromMegabytes(QuantityValue megabytes) -#endif - { - decimal value = (decimal) megabytes; - return new Information(value, InformationUnit.Megabyte); - } - - /// - /// Get Information from Pebibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibits(double pebibits) -#else - public static Information FromPebibits(QuantityValue pebibits) -#endif - { - decimal value = (decimal) pebibits; - return new Information(value, InformationUnit.Pebibit); - } - - /// - /// Get Information from Pebibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibytes(double pebibytes) -#else - public static Information FromPebibytes(QuantityValue pebibytes) -#endif - { - decimal value = (decimal) pebibytes; - return new Information(value, InformationUnit.Pebibyte); - } - - /// - /// Get Information from Petabits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabits(double petabits) -#else - public static Information FromPetabits(QuantityValue petabits) -#endif - { - decimal value = (decimal) petabits; - return new Information(value, InformationUnit.Petabit); - } - - /// - /// Get Information from Petabytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabytes(double petabytes) -#else - public static Information FromPetabytes(QuantityValue petabytes) -#endif - { - decimal value = (decimal) petabytes; - return new Information(value, InformationUnit.Petabyte); - } - - /// - /// Get Information from Tebibits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibits(double tebibits) -#else - public static Information FromTebibits(QuantityValue tebibits) -#endif - { - decimal value = (decimal) tebibits; - return new Information(value, InformationUnit.Tebibit); - } - - /// - /// Get Information from Tebibytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibytes(double tebibytes) -#else - public static Information FromTebibytes(QuantityValue tebibytes) -#endif - { - decimal value = (decimal) tebibytes; - return new Information(value, InformationUnit.Tebibyte); - } - - /// - /// Get Information from Terabits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabits(double terabits) -#else - public static Information FromTerabits(QuantityValue terabits) -#endif - { - decimal value = (decimal) terabits; - return new Information(value, InformationUnit.Terabit); - } - - /// - /// Get Information from Terabytes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabytes(double terabytes) -#else - public static Information FromTerabytes(QuantityValue terabytes) -#endif - { - decimal value = (decimal) terabytes; - return new Information(value, InformationUnit.Terabyte); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Information unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Information From(double value, InformationUnit fromUnit) -#else - public static Information From(QuantityValue value, InformationUnit fromUnit) -#endif - { - return new Information((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(InformationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Information)) throw new ArgumentException("Expected type Information.", nameof(obj)); - - return CompareTo((Information)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Information other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - public override bool Equals(object obj) - { - if(obj is null || !(obj is Information)) - return false; - - var objQuantity = (Information)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Information by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Information, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Information other, Information maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Information. - public override int GetHashCode() - { - return new { type = typeof(Information), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(InformationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Information to another Information with the unit representation . - /// - /// A Information with the specified unit. - public Information ToUnit(InformationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Information(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case InformationUnit.Bit: return _value; - case InformationUnit.Byte: return _value*8m; - case InformationUnit.Exabit: return (_value) * 1e18m; - case InformationUnit.Exabyte: return (_value*8m) * 1e18m; - case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (_value) * 1e9m; - case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; - case InformationUnit.Kibibit: return (_value) * 1024m; - case InformationUnit.Kibibyte: return (_value*8m) * 1024m; - case InformationUnit.Kilobit: return (_value) * 1e3m; - case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; - case InformationUnit.Mebibit: return (_value) * (1024m * 1024); - case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); - case InformationUnit.Megabit: return (_value) * 1e6m; - case InformationUnit.Megabyte: return (_value*8m) * 1e6m; - case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (_value) * 1e15m; - case InformationUnit.Petabyte: return (_value*8m) * 1e15m; - case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (_value) * 1e12m; - case InformationUnit.Terabyte: return (_value*8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(InformationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case InformationUnit.Bit: return baseUnitValue; - case InformationUnit.Byte: return baseUnitValue/8m; - case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; - case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; - case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; - case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; - case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; - case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; - case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; - case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; - case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); - case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); - case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; - case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; - case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; - case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; - case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; - case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Information Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Information result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static InformationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Bit - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static InformationUnit ToStringDefaultUnit { get; set; } = InformationUnit.Bit; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(InformationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Information - /// - public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Information - /// - public static Information MinValue => new Information(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Information.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Information.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs b/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs deleted file mode 100644 index a74974d31f..0000000000 --- a/Common/GeneratedCode/Quantities/Irradiance.Common.g.cs +++ /dev/null @@ -1,511 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Irradiance : IQuantity -#else - public partial struct Irradiance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradianceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Irradiance() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit WattPerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Irradiance(double wattspersquaremeter) - { - _value = Convert.ToDouble(wattspersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Irradiance(double numericValue, IrradianceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. - /// - /// Value assuming base unit WattPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Irradiance(long wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. - /// - /// Value assuming base unit WattPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Irradiance(decimal wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Irradiance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Irradiance quantity. - /// - public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); - - /// - /// Get Irradiance in KilowattsPerSquareMeter. - /// - public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); - - /// - /// Get Irradiance in WattsPerSquareMeter. - /// - public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static Irradiance Zero => new Irradiance(0, BaseUnit); - - /// - /// Get Irradiance from KilowattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) -#else - public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) -#endif - { - double value = (double) kilowattspersquaremeter; - return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); - } - - /// - /// Get Irradiance from WattsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) -#else - public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) -#endif - { - double value = (double) wattspersquaremeter; - return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiance From(double value, IrradianceUnit fromUnit) -#else - public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) -#endif - { - return new Irradiance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradianceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Irradiance)) throw new ArgumentException("Expected type Irradiance.", nameof(obj)); - - return CompareTo((Irradiance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Irradiance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Irradiance)) - return false; - - var objQuantity = (Irradiance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Irradiance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Irradiance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Irradiance other, Irradiance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiance. - public override int GetHashCode() - { - return new { type = typeof(Irradiance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradianceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiance to another Irradiance with the unit representation . - /// - /// A Irradiance with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case IrradianceUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradianceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradianceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is WattPerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static IrradianceUnit ToStringDefaultUnit { get; set; } = IrradianceUnit.WattPerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IrradianceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Irradiance - /// - public static Irradiance MaxValue => new Irradiance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Irradiance - /// - public static Irradiance MinValue => new Irradiance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Irradiance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs b/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs deleted file mode 100644 index f9f5dcd450..0000000000 --- a/Common/GeneratedCode/Quantities/Irradiation.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Irradiation : IQuantity -#else - public partial struct Irradiation : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradiationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Irradiation() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Irradiation(double joulespersquaremeter) - { - _value = Convert.ToDouble(joulespersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Irradiation(double numericValue, IrradiationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerSquareMeter. - /// - /// Value assuming base unit JoulePerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Irradiation(long joulespersquaremeter) : this(Convert.ToDouble(joulespersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerSquareMeter. - /// - /// Value assuming base unit JoulePerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Irradiation(decimal joulespersquaremeter) : this(Convert.ToDouble(joulespersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Irradiation; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Irradiation quantity. - /// - public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); - - /// - /// Get Irradiation in JoulesPerSquareMeter. - /// - public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); - - /// - /// Get Irradiation in KilowattHoursPerSquareMeter. - /// - public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); - - /// - /// Get Irradiation in WattHoursPerSquareMeter. - /// - public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. - /// - public static Irradiation Zero => new Irradiation(0, BaseUnit); - - /// - /// Get Irradiation from JoulesPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) -#else - public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) -#endif - { - double value = (double) joulespersquaremeter; - return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); - } - - /// - /// Get Irradiation from KilowattHoursPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) -#else - public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) -#endif - { - double value = (double) kilowatthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); - } - - /// - /// Get Irradiation from WattHoursPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) -#else - public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) -#endif - { - double value = (double) watthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiation unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiation From(double value, IrradiationUnit fromUnit) -#else - public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) -#endif - { - return new Irradiation((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradiationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Irradiation)) throw new ArgumentException("Expected type Irradiation.", nameof(obj)); - - return CompareTo((Irradiation)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Irradiation other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiation, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Irradiation)) - return false; - - var objQuantity = (Irradiation)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Irradiation by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Irradiation, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Irradiation other, Irradiation maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiation. - public override int GetHashCode() - { - return new { type = typeof(Irradiation), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradiationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiation to another Irradiation with the unit representation . - /// - /// A Irradiation with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiation(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IrradiationUnit.JoulePerSquareMeter: return _value; - case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; - case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradiationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; - case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; - case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiation Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiation result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradiationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static IrradiationUnit ToStringDefaultUnit { get; set; } = IrradiationUnit.JoulePerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(IrradiationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Irradiation - /// - public static Irradiation MaxValue => new Irradiation(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Irradiation - /// - public static Irradiation MinValue => new Irradiation(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Irradiation.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiation.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs b/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs deleted file mode 100644 index 76b96b9df4..0000000000 --- a/Common/GeneratedCode/Quantities/KinematicViscosity.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class KinematicViscosity : IQuantity -#else - public partial struct KinematicViscosity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly KinematicViscosityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static KinematicViscosity() - { - BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit SquareMeterPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public KinematicViscosity(double squaremeterspersecond) - { - _value = Convert.ToDouble(squaremeterspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - KinematicViscosity(double numericValue, KinematicViscosityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit SquareMeterPerSecond. - /// - /// Value assuming base unit SquareMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - KinematicViscosity(long squaremeterspersecond) : this(Convert.ToDouble(squaremeterspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit SquareMeterPerSecond. - /// - /// Value assuming base unit SquareMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - KinematicViscosity(decimal squaremeterspersecond) : this(Convert.ToDouble(squaremeterspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.KinematicViscosity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the KinematicViscosity quantity. - /// - public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); - - /// - /// Get KinematicViscosity in Centistokes. - /// - public double Centistokes => As(KinematicViscosityUnit.Centistokes); - - /// - /// Get KinematicViscosity in Decistokes. - /// - public double Decistokes => As(KinematicViscosityUnit.Decistokes); - - /// - /// Get KinematicViscosity in Kilostokes. - /// - public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); - - /// - /// Get KinematicViscosity in Microstokes. - /// - public double Microstokes => As(KinematicViscosityUnit.Microstokes); - - /// - /// Get KinematicViscosity in Millistokes. - /// - public double Millistokes => As(KinematicViscosityUnit.Millistokes); - - /// - /// Get KinematicViscosity in Nanostokes. - /// - public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); - - /// - /// Get KinematicViscosity in SquareMetersPerSecond. - /// - public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); - - /// - /// Get KinematicViscosity in Stokes. - /// - public double Stokes => As(KinematicViscosityUnit.Stokes); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. - /// - public static KinematicViscosity Zero => new KinematicViscosity(0, BaseUnit); - - /// - /// Get KinematicViscosity from Centistokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromCentistokes(double centistokes) -#else - public static KinematicViscosity FromCentistokes(QuantityValue centistokes) -#endif - { - double value = (double) centistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); - } - - /// - /// Get KinematicViscosity from Decistokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromDecistokes(double decistokes) -#else - public static KinematicViscosity FromDecistokes(QuantityValue decistokes) -#endif - { - double value = (double) decistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); - } - - /// - /// Get KinematicViscosity from Kilostokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromKilostokes(double kilostokes) -#else - public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) -#endif - { - double value = (double) kilostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); - } - - /// - /// Get KinematicViscosity from Microstokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMicrostokes(double microstokes) -#else - public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) -#endif - { - double value = (double) microstokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); - } - - /// - /// Get KinematicViscosity from Millistokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMillistokes(double millistokes) -#else - public static KinematicViscosity FromMillistokes(QuantityValue millistokes) -#endif - { - double value = (double) millistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); - } - - /// - /// Get KinematicViscosity from Nanostokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromNanostokes(double nanostokes) -#else - public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) -#endif - { - double value = (double) nanostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); - } - - /// - /// Get KinematicViscosity from SquareMetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) -#else - public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) -#endif - { - double value = (double) squaremeterspersecond; - return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); - } - - /// - /// Get KinematicViscosity from Stokes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromStokes(double stokes) -#else - public static KinematicViscosity FromStokes(QuantityValue stokes) -#endif - { - double value = (double) stokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// KinematicViscosity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static KinematicViscosity From(double value, KinematicViscosityUnit fromUnit) -#else - public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) -#endif - { - return new KinematicViscosity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(KinematicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is KinematicViscosity)) throw new ArgumentException("Expected type KinematicViscosity.", nameof(obj)); - - return CompareTo((KinematicViscosity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(KinematicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(KinematicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is KinematicViscosity)) - return false; - - var objQuantity = (KinematicViscosity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another KinematicViscosity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(KinematicViscosity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(KinematicViscosity other, KinematicViscosity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current KinematicViscosity. - public override int GetHashCode() - { - return new { type = typeof(KinematicViscosity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . - /// - /// A KinematicViscosity with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new KinematicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; - case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; - case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; - case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; - case KinematicViscosityUnit.SquareMeterPerSecond: return _value; - case KinematicViscosityUnit.Stokes: return _value/1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(KinematicViscosityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; - case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; - case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; - case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; - case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; - case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static KinematicViscosity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static KinematicViscosityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is SquareMeterPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static KinematicViscosityUnit ToStringDefaultUnit { get; set; } = KinematicViscosityUnit.SquareMeterPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(KinematicViscosityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of KinematicViscosity - /// - public static KinematicViscosity MaxValue => new KinematicViscosity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of KinematicViscosity - /// - public static KinematicViscosity MinValue => new KinematicViscosity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => KinematicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs b/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs deleted file mode 100644 index e305ba5321..0000000000 --- a/Common/GeneratedCode/Quantities/LapseRate.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LapseRate : IQuantity -#else - public partial struct LapseRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LapseRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LapseRate() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit DegreeCelsiusPerKilometer. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public LapseRate(double degreescelciusperkilometer) - { - _value = Convert.ToDouble(degreescelciusperkilometer); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - LapseRate(double numericValue, LapseRateUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerKilometer. - /// - /// Value assuming base unit DegreeCelsiusPerKilometer. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LapseRate(long degreescelciusperkilometer) : this(Convert.ToDouble(degreescelciusperkilometer), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerKilometer. - /// - /// Value assuming base unit DegreeCelsiusPerKilometer. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LapseRate(decimal degreescelciusperkilometer) : this(Convert.ToDouble(degreescelciusperkilometer), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LapseRate; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LapseRate quantity. - /// - public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); - - /// - /// Get LapseRate in DegreesCelciusPerKilometer. - /// - public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. - /// - public static LapseRate Zero => new LapseRate(0, BaseUnit); - - /// - /// Get LapseRate from DegreesCelciusPerKilometer. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) -#else - public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) -#endif - { - double value = (double) degreescelciusperkilometer; - return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LapseRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LapseRate From(double value, LapseRateUnit fromUnit) -#else - public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) -#endif - { - return new LapseRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LapseRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LapseRate)) throw new ArgumentException("Expected type LapseRate.", nameof(obj)); - - return CompareTo((LapseRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LapseRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LapseRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is LapseRate)) - return false; - - var objQuantity = (LapseRate)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another LapseRate by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(LapseRate, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(LapseRate other, LapseRate maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LapseRate. - public override int GetHashCode() - { - return new { type = typeof(LapseRate), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LapseRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LapseRate to another LapseRate with the unit representation . - /// - /// A LapseRate with the specified unit. - public LapseRate ToUnit(LapseRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LapseRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LapseRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LapseRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LapseRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LapseRateUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is DegreeCelsiusPerKilometer - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LapseRateUnit ToStringDefaultUnit { get; set; } = LapseRateUnit.DegreeCelsiusPerKilometer; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LapseRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LapseRate - /// - public static LapseRate MaxValue => new LapseRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LapseRate - /// - public static LapseRate MinValue => new LapseRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LapseRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LapseRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Length.Common.g.cs b/Common/GeneratedCode/Quantities/Length.Common.g.cs deleted file mode 100644 index c038a148a0..0000000000 --- a/Common/GeneratedCode/Quantities/Length.Common.g.cs +++ /dev/null @@ -1,931 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Length : IQuantity -#else - public partial struct Length : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Length() - { - BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Meter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Length(double meters) - { - _value = Convert.ToDouble(meters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Length(double numericValue, LengthUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Meter. - /// - /// Value assuming base unit Meter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Length(long meters) : this(Convert.ToDouble(meters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Meter. - /// - /// Value assuming base unit Meter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Length(decimal meters) : this(Convert.ToDouble(meters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Length; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LengthUnit BaseUnit => LengthUnit.Meter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Length quantity. - /// - public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); - - /// - /// Get Length in Centimeters. - /// - public double Centimeters => As(LengthUnit.Centimeter); - - /// - /// Get Length in Decimeters. - /// - public double Decimeters => As(LengthUnit.Decimeter); - - /// - /// Get Length in DtpPicas. - /// - public double DtpPicas => As(LengthUnit.DtpPica); - - /// - /// Get Length in DtpPoints. - /// - public double DtpPoints => As(LengthUnit.DtpPoint); - - /// - /// Get Length in Fathoms. - /// - public double Fathoms => As(LengthUnit.Fathom); - - /// - /// Get Length in Feet. - /// - public double Feet => As(LengthUnit.Foot); - - /// - /// Get Length in Inches. - /// - public double Inches => As(LengthUnit.Inch); - - /// - /// Get Length in Kilometers. - /// - public double Kilometers => As(LengthUnit.Kilometer); - - /// - /// Get Length in Meters. - /// - public double Meters => As(LengthUnit.Meter); - - /// - /// Get Length in Microinches. - /// - public double Microinches => As(LengthUnit.Microinch); - - /// - /// Get Length in Micrometers. - /// - public double Micrometers => As(LengthUnit.Micrometer); - - /// - /// Get Length in Mils. - /// - public double Mils => As(LengthUnit.Mil); - - /// - /// Get Length in Miles. - /// - public double Miles => As(LengthUnit.Mile); - - /// - /// Get Length in Millimeters. - /// - public double Millimeters => As(LengthUnit.Millimeter); - - /// - /// Get Length in Nanometers. - /// - public double Nanometers => As(LengthUnit.Nanometer); - - /// - /// Get Length in NauticalMiles. - /// - public double NauticalMiles => As(LengthUnit.NauticalMile); - - /// - /// Get Length in PrinterPicas. - /// - public double PrinterPicas => As(LengthUnit.PrinterPica); - - /// - /// Get Length in PrinterPoints. - /// - public double PrinterPoints => As(LengthUnit.PrinterPoint); - - /// - /// Get Length in Shackles. - /// - public double Shackles => As(LengthUnit.Shackle); - - /// - /// Get Length in Twips. - /// - public double Twips => As(LengthUnit.Twip); - - /// - /// Get Length in UsSurveyFeet. - /// - public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); - - /// - /// Get Length in Yards. - /// - public double Yards => As(LengthUnit.Yard); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Meter. - /// - public static Length Zero => new Length(0, BaseUnit); - - /// - /// Get Length from Centimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromCentimeters(double centimeters) -#else - public static Length FromCentimeters(QuantityValue centimeters) -#endif - { - double value = (double) centimeters; - return new Length(value, LengthUnit.Centimeter); - } - - /// - /// Get Length from Decimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDecimeters(double decimeters) -#else - public static Length FromDecimeters(QuantityValue decimeters) -#endif - { - double value = (double) decimeters; - return new Length(value, LengthUnit.Decimeter); - } - - /// - /// Get Length from DtpPicas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPicas(double dtppicas) -#else - public static Length FromDtpPicas(QuantityValue dtppicas) -#endif - { - double value = (double) dtppicas; - return new Length(value, LengthUnit.DtpPica); - } - - /// - /// Get Length from DtpPoints. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPoints(double dtppoints) -#else - public static Length FromDtpPoints(QuantityValue dtppoints) -#endif - { - double value = (double) dtppoints; - return new Length(value, LengthUnit.DtpPoint); - } - - /// - /// Get Length from Fathoms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFathoms(double fathoms) -#else - public static Length FromFathoms(QuantityValue fathoms) -#endif - { - double value = (double) fathoms; - return new Length(value, LengthUnit.Fathom); - } - - /// - /// Get Length from Feet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFeet(double feet) -#else - public static Length FromFeet(QuantityValue feet) -#endif - { - double value = (double) feet; - return new Length(value, LengthUnit.Foot); - } - - /// - /// Get Length from Inches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromInches(double inches) -#else - public static Length FromInches(QuantityValue inches) -#endif - { - double value = (double) inches; - return new Length(value, LengthUnit.Inch); - } - - /// - /// Get Length from Kilometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromKilometers(double kilometers) -#else - public static Length FromKilometers(QuantityValue kilometers) -#endif - { - double value = (double) kilometers; - return new Length(value, LengthUnit.Kilometer); - } - - /// - /// Get Length from Meters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMeters(double meters) -#else - public static Length FromMeters(QuantityValue meters) -#endif - { - double value = (double) meters; - return new Length(value, LengthUnit.Meter); - } - - /// - /// Get Length from Microinches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicroinches(double microinches) -#else - public static Length FromMicroinches(QuantityValue microinches) -#endif - { - double value = (double) microinches; - return new Length(value, LengthUnit.Microinch); - } - - /// - /// Get Length from Micrometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicrometers(double micrometers) -#else - public static Length FromMicrometers(QuantityValue micrometers) -#endif - { - double value = (double) micrometers; - return new Length(value, LengthUnit.Micrometer); - } - - /// - /// Get Length from Mils. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMils(double mils) -#else - public static Length FromMils(QuantityValue mils) -#endif - { - double value = (double) mils; - return new Length(value, LengthUnit.Mil); - } - - /// - /// Get Length from Miles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMiles(double miles) -#else - public static Length FromMiles(QuantityValue miles) -#endif - { - double value = (double) miles; - return new Length(value, LengthUnit.Mile); - } - - /// - /// Get Length from Millimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMillimeters(double millimeters) -#else - public static Length FromMillimeters(QuantityValue millimeters) -#endif - { - double value = (double) millimeters; - return new Length(value, LengthUnit.Millimeter); - } - - /// - /// Get Length from Nanometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNanometers(double nanometers) -#else - public static Length FromNanometers(QuantityValue nanometers) -#endif - { - double value = (double) nanometers; - return new Length(value, LengthUnit.Nanometer); - } - - /// - /// Get Length from NauticalMiles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNauticalMiles(double nauticalmiles) -#else - public static Length FromNauticalMiles(QuantityValue nauticalmiles) -#endif - { - double value = (double) nauticalmiles; - return new Length(value, LengthUnit.NauticalMile); - } - - /// - /// Get Length from PrinterPicas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPicas(double printerpicas) -#else - public static Length FromPrinterPicas(QuantityValue printerpicas) -#endif - { - double value = (double) printerpicas; - return new Length(value, LengthUnit.PrinterPica); - } - - /// - /// Get Length from PrinterPoints. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPoints(double printerpoints) -#else - public static Length FromPrinterPoints(QuantityValue printerpoints) -#endif - { - double value = (double) printerpoints; - return new Length(value, LengthUnit.PrinterPoint); - } - - /// - /// Get Length from Shackles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromShackles(double shackles) -#else - public static Length FromShackles(QuantityValue shackles) -#endif - { - double value = (double) shackles; - return new Length(value, LengthUnit.Shackle); - } - - /// - /// Get Length from Twips. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromTwips(double twips) -#else - public static Length FromTwips(QuantityValue twips) -#endif - { - double value = (double) twips; - return new Length(value, LengthUnit.Twip); - } - - /// - /// Get Length from UsSurveyFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromUsSurveyFeet(double ussurveyfeet) -#else - public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) -#endif - { - double value = (double) ussurveyfeet; - return new Length(value, LengthUnit.UsSurveyFoot); - } - - /// - /// Get Length from Yards. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromYards(double yards) -#else - public static Length FromYards(QuantityValue yards) -#endif - { - double value = (double) yards; - return new Length(value, LengthUnit.Yard); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Length unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Length From(double value, LengthUnit fromUnit) -#else - public static Length From(QuantityValue value, LengthUnit fromUnit) -#endif - { - return new Length((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Length)) throw new ArgumentException("Expected type Length.", nameof(obj)); - - return CompareTo((Length)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Length other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Length, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Length)) - return false; - - var objQuantity = (Length)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Length by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Length, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Length other, Length maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Length. - public override int GetHashCode() - { - return new { type = typeof(Length), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Length to another Length with the unit representation . - /// - /// A Length with the specified unit. - public Length ToUnit(LengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Length(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LengthUnit.Centimeter: return (_value) * 1e-2d; - case LengthUnit.Decimeter: return (_value) * 1e-1d; - case LengthUnit.DtpPica: return _value/236.220472441; - case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; - case LengthUnit.Fathom: return _value*1.8288; - case LengthUnit.Foot: return _value*0.3048; - case LengthUnit.Inch: return _value*2.54e-2; - case LengthUnit.Kilometer: return (_value) * 1e3d; - case LengthUnit.Meter: return _value; - case LengthUnit.Microinch: return _value*2.54e-8; - case LengthUnit.Micrometer: return (_value) * 1e-6d; - case LengthUnit.Mil: return _value*2.54e-5; - case LengthUnit.Mile: return _value*1609.34; - case LengthUnit.Millimeter: return (_value) * 1e-3d; - case LengthUnit.Nanometer: return (_value) * 1e-9d; - case LengthUnit.NauticalMile: return _value*1852; - case LengthUnit.PrinterPica: return _value/237.106301584; - case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; - case LengthUnit.Shackle: return _value*27.432; - case LengthUnit.Twip: return _value/56692.913385826; - case LengthUnit.UsSurveyFoot: return _value*1200/3937; - case LengthUnit.Yard: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; - case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; - case LengthUnit.DtpPica: return baseUnitValue*236.220472441; - case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; - case LengthUnit.Fathom: return baseUnitValue/1.8288; - case LengthUnit.Foot: return baseUnitValue/0.3048; - case LengthUnit.Inch: return baseUnitValue/2.54e-2; - case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; - case LengthUnit.Meter: return baseUnitValue; - case LengthUnit.Microinch: return baseUnitValue/2.54e-8; - case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; - case LengthUnit.Mil: return baseUnitValue/2.54e-5; - case LengthUnit.Mile: return baseUnitValue/1609.34; - case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; - case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; - case LengthUnit.NauticalMile: return baseUnitValue/1852; - case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; - case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; - case LengthUnit.Shackle: return baseUnitValue/27.432; - case LengthUnit.Twip: return baseUnitValue*56692.913385826; - case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; - case LengthUnit.Yard: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Length Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Length result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LengthUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Meter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LengthUnit ToStringDefaultUnit { get; set; } = LengthUnit.Meter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Length - /// - public static Length MaxValue => new Length(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Length - /// - public static Length MinValue => new Length(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Length.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Length.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Level.Common.g.cs b/Common/GeneratedCode/Quantities/Level.Common.g.cs deleted file mode 100644 index 11d76a138d..0000000000 --- a/Common/GeneratedCode/Quantities/Level.Common.g.cs +++ /dev/null @@ -1,510 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Level : IQuantity -#else - public partial struct Level : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LevelUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Level() - { - } - - /// - /// Creates the quantity with the given value in the base unit Decibel. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Level(double decibels) - { - _value = Convert.ToDouble(decibels); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Level(double numericValue, LevelUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Decibel. - /// - /// Value assuming base unit Decibel. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Level(long decibels) : this(Convert.ToDouble(decibels), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Decibel. - /// - /// Value assuming base unit Decibel. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Level(decimal decibels) : this(Convert.ToDouble(decibels), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Level; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LevelUnit BaseUnit => LevelUnit.Decibel; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Level quantity. - /// - public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); - - /// - /// Get Level in Decibels. - /// - public double Decibels => As(LevelUnit.Decibel); - - /// - /// Get Level in Nepers. - /// - public double Nepers => As(LevelUnit.Neper); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. - /// - public static Level Zero => new Level(0, BaseUnit); - - /// - /// Get Level from Decibels. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromDecibels(double decibels) -#else - public static Level FromDecibels(QuantityValue decibels) -#endif - { - double value = (double) decibels; - return new Level(value, LevelUnit.Decibel); - } - - /// - /// Get Level from Nepers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromNepers(double nepers) -#else - public static Level FromNepers(QuantityValue nepers) -#endif - { - double value = (double) nepers; - return new Level(value, LevelUnit.Neper); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Level unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Level From(double value, LevelUnit fromUnit) -#else - public static Level From(QuantityValue value, LevelUnit fromUnit) -#endif - { - return new Level((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LevelUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Level)) throw new ArgumentException("Expected type Level.", nameof(obj)); - - return CompareTo((Level)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Level other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Level, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Level)) - return false; - - var objQuantity = (Level)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Level by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Level, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Level other, Level maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Level. - public override int GetHashCode() - { - return new { type = typeof(Level), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LevelUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Level to another Level with the unit representation . - /// - /// A Level with the specified unit. - public Level ToUnit(LevelUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Level(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LevelUnit.Decibel: return _value; - case LevelUnit.Neper: return (1/0.115129254)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LevelUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LevelUnit.Decibel: return baseUnitValue; - case LevelUnit.Neper: return 0.115129254*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Level Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Level result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LevelUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Decibel - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LevelUnit ToStringDefaultUnit { get; set; } = LevelUnit.Decibel; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LevelUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Level - /// - public static Level MaxValue => new Level(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Level - /// - public static Level MinValue => new Level(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Level.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Level.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs b/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs deleted file mode 100644 index db00a79a9a..0000000000 --- a/Common/GeneratedCode/Quantities/LinearDensity.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LinearDensity : IQuantity -#else - public partial struct LinearDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LinearDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LinearDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public LinearDensity(double kilogramspermeter) - { - _value = Convert.ToDouble(kilogramspermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - LinearDensity(double numericValue, LinearDensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerMeter. - /// - /// Value assuming base unit KilogramPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LinearDensity(long kilogramspermeter) : this(Convert.ToDouble(kilogramspermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerMeter. - /// - /// Value assuming base unit KilogramPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LinearDensity(decimal kilogramspermeter) : this(Convert.ToDouble(kilogramspermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LinearDensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LinearDensity quantity. - /// - public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); - - /// - /// Get LinearDensity in GramsPerMeter. - /// - public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); - - /// - /// Get LinearDensity in KilogramsPerMeter. - /// - public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); - - /// - /// Get LinearDensity in PoundsPerFoot. - /// - public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. - /// - public static LinearDensity Zero => new LinearDensity(0, BaseUnit); - - /// - /// Get LinearDensity from GramsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromGramsPerMeter(double gramspermeter) -#else - public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) -#endif - { - double value = (double) gramspermeter; - return new LinearDensity(value, LinearDensityUnit.GramPerMeter); - } - - /// - /// Get LinearDensity from KilogramsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) -#else - public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) -#endif - { - double value = (double) kilogramspermeter; - return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); - } - - /// - /// Get LinearDensity from PoundsPerFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromPoundsPerFoot(double poundsperfoot) -#else - public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) -#endif - { - double value = (double) poundsperfoot; - return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LinearDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LinearDensity From(double value, LinearDensityUnit fromUnit) -#else - public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) -#endif - { - return new LinearDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LinearDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LinearDensity)) throw new ArgumentException("Expected type LinearDensity.", nameof(obj)); - - return CompareTo((LinearDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LinearDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LinearDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is LinearDensity)) - return false; - - var objQuantity = (LinearDensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another LinearDensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(LinearDensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(LinearDensity other, LinearDensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearDensity. - public override int GetHashCode() - { - return new { type = typeof(LinearDensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LinearDensity to another LinearDensity with the unit representation . - /// - /// A LinearDensity with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LinearDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LinearDensityUnit.GramPerMeter: return _value*1e-3; - case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; - case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LinearDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; - case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; - case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LinearDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LinearDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LinearDensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LinearDensityUnit ToStringDefaultUnit { get; set; } = LinearDensityUnit.KilogramPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LinearDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LinearDensity - /// - public static LinearDensity MaxValue => new LinearDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LinearDensity - /// - public static LinearDensity MinValue => new LinearDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LinearDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LinearDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs b/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs deleted file mode 100644 index 231b16e213..0000000000 --- a/Common/GeneratedCode/Quantities/LuminousFlux.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LuminousFlux : IQuantity -#else - public partial struct LuminousFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LuminousFlux() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given value in the base unit Lumen. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public LuminousFlux(double lumens) - { - _value = Convert.ToDouble(lumens); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - LuminousFlux(double numericValue, LuminousFluxUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Lumen. - /// - /// Value assuming base unit Lumen. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LuminousFlux(long lumens) : this(Convert.ToDouble(lumens), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Lumen. - /// - /// Value assuming base unit Lumen. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LuminousFlux(decimal lumens) : this(Convert.ToDouble(lumens), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LuminousFlux; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LuminousFlux quantity. - /// - public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); - - /// - /// Get LuminousFlux in Lumens. - /// - public double Lumens => As(LuminousFluxUnit.Lumen); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. - /// - public static LuminousFlux Zero => new LuminousFlux(0, BaseUnit); - - /// - /// Get LuminousFlux from Lumens. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousFlux FromLumens(double lumens) -#else - public static LuminousFlux FromLumens(QuantityValue lumens) -#endif - { - double value = (double) lumens; - return new LuminousFlux(value, LuminousFluxUnit.Lumen); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) -#else - public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) -#endif - { - return new LuminousFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LuminousFlux)) throw new ArgumentException("Expected type LuminousFlux.", nameof(obj)); - - return CompareTo((LuminousFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LuminousFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is LuminousFlux)) - return false; - - var objQuantity = (LuminousFlux)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another LuminousFlux by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(LuminousFlux, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(LuminousFlux other, LuminousFlux maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousFlux. - public override int GetHashCode() - { - return new { type = typeof(LuminousFlux), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousFlux to another LuminousFlux with the unit representation . - /// - /// A LuminousFlux with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LuminousFluxUnit.Lumen: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousFluxUnit.Lumen: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousFluxUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Lumen - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LuminousFluxUnit ToStringDefaultUnit { get; set; } = LuminousFluxUnit.Lumen; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LuminousFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LuminousFlux - /// - public static LuminousFlux MaxValue => new LuminousFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LuminousFlux - /// - public static LuminousFlux MinValue => new LuminousFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LuminousFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs b/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs deleted file mode 100644 index 5e090cb729..0000000000 --- a/Common/GeneratedCode/Quantities/LuminousIntensity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class LuminousIntensity : IQuantity -#else - public partial struct LuminousIntensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousIntensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static LuminousIntensity() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - } - - /// - /// Creates the quantity with the given value in the base unit Candela. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public LuminousIntensity(double candela) - { - _value = Convert.ToDouble(candela); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - LuminousIntensity(double numericValue, LuminousIntensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Candela. - /// - /// Value assuming base unit Candela. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LuminousIntensity(long candela) : this(Convert.ToDouble(candela), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Candela. - /// - /// Value assuming base unit Candela. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - LuminousIntensity(decimal candela) : this(Convert.ToDouble(candela), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.LuminousIntensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the LuminousIntensity quantity. - /// - public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); - - /// - /// Get LuminousIntensity in Candela. - /// - public double Candela => As(LuminousIntensityUnit.Candela); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Candela. - /// - public static LuminousIntensity Zero => new LuminousIntensity(0, BaseUnit); - - /// - /// Get LuminousIntensity from Candela. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousIntensity FromCandela(double candela) -#else - public static LuminousIntensity FromCandela(QuantityValue candela) -#endif - { - double value = (double) candela; - return new LuminousIntensity(value, LuminousIntensityUnit.Candela); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousIntensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousIntensity From(double value, LuminousIntensityUnit fromUnit) -#else - public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) -#endif - { - return new LuminousIntensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousIntensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is LuminousIntensity)) throw new ArgumentException("Expected type LuminousIntensity.", nameof(obj)); - - return CompareTo((LuminousIntensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(LuminousIntensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousIntensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is LuminousIntensity)) - return false; - - var objQuantity = (LuminousIntensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another LuminousIntensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(LuminousIntensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(LuminousIntensity other, LuminousIntensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousIntensity. - public override int GetHashCode() - { - return new { type = typeof(LuminousIntensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . - /// - /// A LuminousIntensity with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousIntensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LuminousIntensityUnit.Candela: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousIntensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousIntensityUnit.Candela: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousIntensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousIntensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Candela - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static LuminousIntensityUnit ToStringDefaultUnit { get; set; } = LuminousIntensityUnit.Candela; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(LuminousIntensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of LuminousIntensity - /// - public static LuminousIntensity MaxValue => new LuminousIntensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of LuminousIntensity - /// - public static LuminousIntensity MinValue => new LuminousIntensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => LuminousIntensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs b/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs deleted file mode 100644 index 90c00171c9..0000000000 --- a/Common/GeneratedCode/Quantities/MagneticField.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MagneticField : IQuantity -#else - public partial struct MagneticField : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFieldUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MagneticField() - { - BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Tesla. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MagneticField(double teslas) - { - _value = Convert.ToDouble(teslas); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MagneticField(double numericValue, MagneticFieldUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Tesla. - /// - /// Value assuming base unit Tesla. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MagneticField(long teslas) : this(Convert.ToDouble(teslas), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Tesla. - /// - /// Value assuming base unit Tesla. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MagneticField(decimal teslas) : this(Convert.ToDouble(teslas), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MagneticField; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MagneticField quantity. - /// - public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); - - /// - /// Get MagneticField in Microteslas. - /// - public double Microteslas => As(MagneticFieldUnit.Microtesla); - - /// - /// Get MagneticField in Milliteslas. - /// - public double Milliteslas => As(MagneticFieldUnit.Millitesla); - - /// - /// Get MagneticField in Nanoteslas. - /// - public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); - - /// - /// Get MagneticField in Teslas. - /// - public double Teslas => As(MagneticFieldUnit.Tesla); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. - /// - public static MagneticField Zero => new MagneticField(0, BaseUnit); - - /// - /// Get MagneticField from Microteslas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromMicroteslas(double microteslas) -#else - public static MagneticField FromMicroteslas(QuantityValue microteslas) -#endif - { - double value = (double) microteslas; - return new MagneticField(value, MagneticFieldUnit.Microtesla); - } - - /// - /// Get MagneticField from Milliteslas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromMilliteslas(double milliteslas) -#else - public static MagneticField FromMilliteslas(QuantityValue milliteslas) -#endif - { - double value = (double) milliteslas; - return new MagneticField(value, MagneticFieldUnit.Millitesla); - } - - /// - /// Get MagneticField from Nanoteslas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromNanoteslas(double nanoteslas) -#else - public static MagneticField FromNanoteslas(QuantityValue nanoteslas) -#endif - { - double value = (double) nanoteslas; - return new MagneticField(value, MagneticFieldUnit.Nanotesla); - } - - /// - /// Get MagneticField from Teslas. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromTeslas(double teslas) -#else - public static MagneticField FromTeslas(QuantityValue teslas) -#endif - { - double value = (double) teslas; - return new MagneticField(value, MagneticFieldUnit.Tesla); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticField unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticField From(double value, MagneticFieldUnit fromUnit) -#else - public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) -#endif - { - return new MagneticField((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MagneticField)) throw new ArgumentException("Expected type MagneticField.", nameof(obj)); - - return CompareTo((MagneticField)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MagneticField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MagneticField)) - return false; - - var objQuantity = (MagneticField)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MagneticField by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MagneticField, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MagneticField other, MagneticField maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticField. - public override int GetHashCode() - { - return new { type = typeof(MagneticField), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticField to another MagneticField with the unit representation . - /// - /// A MagneticField with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagneticFieldUnit.Microtesla: return (_value) * 1e-6d; - 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.Microtesla: return (baseUnitValue) / 1e-6d; - 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 Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticField Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticField result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFieldUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Tesla - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MagneticFieldUnit ToStringDefaultUnit { get; set; } = MagneticFieldUnit.Tesla; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagneticFieldUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MagneticField - /// - public static MagneticField MaxValue => new MagneticField(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MagneticField - /// - public static MagneticField MinValue => new MagneticField(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MagneticField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticField.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs b/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs deleted file mode 100644 index 11743f090b..0000000000 --- a/Common/GeneratedCode/Quantities/MagneticFlux.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MagneticFlux : IQuantity -#else - public partial struct MagneticFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MagneticFlux() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Weber. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MagneticFlux(double webers) - { - _value = Convert.ToDouble(webers); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MagneticFlux(double numericValue, MagneticFluxUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Weber. - /// - /// Value assuming base unit Weber. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MagneticFlux(long webers) : this(Convert.ToDouble(webers), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Weber. - /// - /// Value assuming base unit Weber. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MagneticFlux(decimal webers) : this(Convert.ToDouble(webers), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MagneticFlux; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MagneticFlux quantity. - /// - public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); - - /// - /// Get MagneticFlux in Webers. - /// - public double Webers => As(MagneticFluxUnit.Weber); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Weber. - /// - public static MagneticFlux Zero => new MagneticFlux(0, BaseUnit); - - /// - /// Get MagneticFlux from Webers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticFlux FromWebers(double webers) -#else - public static MagneticFlux FromWebers(QuantityValue webers) -#endif - { - double value = (double) webers; - return new MagneticFlux(value, MagneticFluxUnit.Weber); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) -#else - public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) -#endif - { - return new MagneticFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MagneticFlux)) throw new ArgumentException("Expected type MagneticFlux.", nameof(obj)); - - return CompareTo((MagneticFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MagneticFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MagneticFlux)) - return false; - - var objQuantity = (MagneticFlux)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MagneticFlux by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MagneticFlux, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MagneticFlux other, MagneticFlux maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticFlux. - public override int GetHashCode() - { - return new { type = typeof(MagneticFlux), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticFlux to another MagneticFlux with the unit representation . - /// - /// A MagneticFlux with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagneticFluxUnit.Weber: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagneticFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagneticFluxUnit.Weber: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFluxUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Weber - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MagneticFluxUnit ToStringDefaultUnit { get; set; } = MagneticFluxUnit.Weber; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagneticFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MagneticFlux - /// - public static MagneticFlux MaxValue => new MagneticFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MagneticFlux - /// - public static MagneticFlux MinValue => new MagneticFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MagneticFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs b/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs deleted file mode 100644 index 2f0c772afa..0000000000 --- a/Common/GeneratedCode/Quantities/Magnetization.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Magnetization : IQuantity -#else - public partial struct Magnetization : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagnetizationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Magnetization() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit AmperePerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Magnetization(double amperespermeter) - { - _value = Convert.ToDouble(amperespermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Magnetization(double numericValue, MagnetizationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit AmperePerMeter. - /// - /// Value assuming base unit AmperePerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Magnetization(long amperespermeter) : this(Convert.ToDouble(amperespermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit AmperePerMeter. - /// - /// Value assuming base unit AmperePerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Magnetization(decimal amperespermeter) : this(Convert.ToDouble(amperespermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Magnetization; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Magnetization quantity. - /// - public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); - - /// - /// Get Magnetization in AmperesPerMeter. - /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. - /// - public static Magnetization Zero => new Magnetization(0, BaseUnit); - - /// - /// Get Magnetization from AmperesPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Magnetization FromAmperesPerMeter(double amperespermeter) -#else - public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) -#endif - { - double value = (double) amperespermeter; - return new Magnetization(value, MagnetizationUnit.AmperePerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Magnetization unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Magnetization From(double value, MagnetizationUnit fromUnit) -#else - public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) -#endif - { - return new Magnetization((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagnetizationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Magnetization)) throw new ArgumentException("Expected type Magnetization.", nameof(obj)); - - return CompareTo((Magnetization)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Magnetization other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Magnetization, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Magnetization)) - return false; - - var objQuantity = (Magnetization)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Magnetization by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Magnetization, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Magnetization other, Magnetization maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Magnetization. - public override int GetHashCode() - { - return new { type = typeof(Magnetization), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Magnetization to another Magnetization with the unit representation . - /// - /// A Magnetization with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Magnetization(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagnetizationUnit.AmperePerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagnetizationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagnetizationUnit.AmperePerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Magnetization Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Magnetization result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagnetizationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is AmperePerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MagnetizationUnit ToStringDefaultUnit { get; set; } = MagnetizationUnit.AmperePerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MagnetizationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Magnetization - /// - public static Magnetization MaxValue => new Magnetization(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Magnetization - /// - public static Magnetization MinValue => new Magnetization(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Magnetization.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Magnetization.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Mass.Common.g.cs b/Common/GeneratedCode/Quantities/Mass.Common.g.cs deleted file mode 100644 index 065a1a94b6..0000000000 --- a/Common/GeneratedCode/Quantities/Mass.Common.g.cs +++ /dev/null @@ -1,931 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Mass : IQuantity -#else - public partial struct Mass : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Mass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Kilogram. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Mass(double kilograms) - { - _value = Convert.ToDouble(kilograms); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Mass(double numericValue, MassUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Kilogram. - /// - /// Value assuming base unit Kilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Mass(long kilograms) : this(Convert.ToDouble(kilograms), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Kilogram. - /// - /// Value assuming base unit Kilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Mass(decimal kilograms) : this(Convert.ToDouble(kilograms), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Mass; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MassUnit BaseUnit => MassUnit.Kilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Mass quantity. - /// - public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); - - /// - /// Get Mass in Centigrams. - /// - public double Centigrams => As(MassUnit.Centigram); - - /// - /// Get Mass in Decagrams. - /// - public double Decagrams => As(MassUnit.Decagram); - - /// - /// Get Mass in Decigrams. - /// - public double Decigrams => As(MassUnit.Decigram); - - /// - /// Get Mass in Grams. - /// - public double Grams => As(MassUnit.Gram); - - /// - /// Get Mass in Hectograms. - /// - public double Hectograms => As(MassUnit.Hectogram); - - /// - /// Get Mass in Kilograms. - /// - public double Kilograms => As(MassUnit.Kilogram); - - /// - /// Get Mass in Kilopounds. - /// - public double Kilopounds => As(MassUnit.Kilopound); - - /// - /// Get Mass in Kilotonnes. - /// - public double Kilotonnes => As(MassUnit.Kilotonne); - - /// - /// Get Mass in LongHundredweight. - /// - public double LongHundredweight => As(MassUnit.LongHundredweight); - - /// - /// Get Mass in LongTons. - /// - public double LongTons => As(MassUnit.LongTon); - - /// - /// Get Mass in Megapounds. - /// - public double Megapounds => As(MassUnit.Megapound); - - /// - /// Get Mass in Megatonnes. - /// - public double Megatonnes => As(MassUnit.Megatonne); - - /// - /// Get Mass in Micrograms. - /// - public double Micrograms => As(MassUnit.Microgram); - - /// - /// Get Mass in Milligrams. - /// - public double Milligrams => As(MassUnit.Milligram); - - /// - /// Get Mass in Nanograms. - /// - public double Nanograms => As(MassUnit.Nanogram); - - /// - /// Get Mass in Ounces. - /// - public double Ounces => As(MassUnit.Ounce); - - /// - /// Get Mass in Pounds. - /// - public double Pounds => As(MassUnit.Pound); - - /// - /// Get Mass in ShortHundredweight. - /// - public double ShortHundredweight => As(MassUnit.ShortHundredweight); - - /// - /// Get Mass in ShortTons. - /// - public double ShortTons => As(MassUnit.ShortTon); - - /// - /// Get Mass in Slugs. - /// - public double Slugs => As(MassUnit.Slug); - - /// - /// Get Mass in Stone. - /// - public double Stone => As(MassUnit.Stone); - - /// - /// Get Mass in Tonnes. - /// - public double Tonnes => As(MassUnit.Tonne); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. - /// - public static Mass Zero => new Mass(0, BaseUnit); - - /// - /// Get Mass from Centigrams. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromCentigrams(double centigrams) -#else - public static Mass FromCentigrams(QuantityValue centigrams) -#endif - { - double value = (double) centigrams; - return new Mass(value, MassUnit.Centigram); - } - - /// - /// Get Mass from Decagrams. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecagrams(double decagrams) -#else - public static Mass FromDecagrams(QuantityValue decagrams) -#endif - { - double value = (double) decagrams; - return new Mass(value, MassUnit.Decagram); - } - - /// - /// Get Mass from Decigrams. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecigrams(double decigrams) -#else - public static Mass FromDecigrams(QuantityValue decigrams) -#endif - { - double value = (double) decigrams; - return new Mass(value, MassUnit.Decigram); - } - - /// - /// Get Mass from Grams. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromGrams(double grams) -#else - public static Mass FromGrams(QuantityValue grams) -#endif - { - double value = (double) grams; - return new Mass(value, MassUnit.Gram); - } - - /// - /// Get Mass from Hectograms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromHectograms(double hectograms) -#else - public static Mass FromHectograms(QuantityValue hectograms) -#endif - { - double value = (double) hectograms; - return new Mass(value, MassUnit.Hectogram); - } - - /// - /// Get Mass from Kilograms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilograms(double kilograms) -#else - public static Mass FromKilograms(QuantityValue kilograms) -#endif - { - double value = (double) kilograms; - return new Mass(value, MassUnit.Kilogram); - } - - /// - /// Get Mass from Kilopounds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilopounds(double kilopounds) -#else - public static Mass FromKilopounds(QuantityValue kilopounds) -#endif - { - double value = (double) kilopounds; - return new Mass(value, MassUnit.Kilopound); - } - - /// - /// Get Mass from Kilotonnes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilotonnes(double kilotonnes) -#else - public static Mass FromKilotonnes(QuantityValue kilotonnes) -#endif - { - double value = (double) kilotonnes; - return new Mass(value, MassUnit.Kilotonne); - } - - /// - /// Get Mass from LongHundredweight. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongHundredweight(double longhundredweight) -#else - public static Mass FromLongHundredweight(QuantityValue longhundredweight) -#endif - { - double value = (double) longhundredweight; - return new Mass(value, MassUnit.LongHundredweight); - } - - /// - /// Get Mass from LongTons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongTons(double longtons) -#else - public static Mass FromLongTons(QuantityValue longtons) -#endif - { - double value = (double) longtons; - return new Mass(value, MassUnit.LongTon); - } - - /// - /// Get Mass from Megapounds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegapounds(double megapounds) -#else - public static Mass FromMegapounds(QuantityValue megapounds) -#endif - { - double value = (double) megapounds; - return new Mass(value, MassUnit.Megapound); - } - - /// - /// Get Mass from Megatonnes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegatonnes(double megatonnes) -#else - public static Mass FromMegatonnes(QuantityValue megatonnes) -#endif - { - double value = (double) megatonnes; - return new Mass(value, MassUnit.Megatonne); - } - - /// - /// Get Mass from Micrograms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMicrograms(double micrograms) -#else - public static Mass FromMicrograms(QuantityValue micrograms) -#endif - { - double value = (double) micrograms; - return new Mass(value, MassUnit.Microgram); - } - - /// - /// Get Mass from Milligrams. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMilligrams(double milligrams) -#else - public static Mass FromMilligrams(QuantityValue milligrams) -#endif - { - double value = (double) milligrams; - return new Mass(value, MassUnit.Milligram); - } - - /// - /// Get Mass from Nanograms. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromNanograms(double nanograms) -#else - public static Mass FromNanograms(QuantityValue nanograms) -#endif - { - double value = (double) nanograms; - return new Mass(value, MassUnit.Nanogram); - } - - /// - /// Get Mass from Ounces. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromOunces(double ounces) -#else - public static Mass FromOunces(QuantityValue ounces) -#endif - { - double value = (double) ounces; - return new Mass(value, MassUnit.Ounce); - } - - /// - /// Get Mass from Pounds. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromPounds(double pounds) -#else - public static Mass FromPounds(QuantityValue pounds) -#endif - { - double value = (double) pounds; - return new Mass(value, MassUnit.Pound); - } - - /// - /// Get Mass from ShortHundredweight. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortHundredweight(double shorthundredweight) -#else - public static Mass FromShortHundredweight(QuantityValue shorthundredweight) -#endif - { - double value = (double) shorthundredweight; - return new Mass(value, MassUnit.ShortHundredweight); - } - - /// - /// Get Mass from ShortTons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortTons(double shorttons) -#else - public static Mass FromShortTons(QuantityValue shorttons) -#endif - { - double value = (double) shorttons; - return new Mass(value, MassUnit.ShortTon); - } - - /// - /// Get Mass from Slugs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromSlugs(double slugs) -#else - public static Mass FromSlugs(QuantityValue slugs) -#endif - { - double value = (double) slugs; - return new Mass(value, MassUnit.Slug); - } - - /// - /// Get Mass from Stone. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromStone(double stone) -#else - public static Mass FromStone(QuantityValue stone) -#endif - { - double value = (double) stone; - return new Mass(value, MassUnit.Stone); - } - - /// - /// Get Mass from Tonnes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromTonnes(double tonnes) -#else - public static Mass FromTonnes(QuantityValue tonnes) -#endif - { - double value = (double) tonnes; - return new Mass(value, MassUnit.Tonne); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Mass unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Mass From(double value, MassUnit fromUnit) -#else - public static Mass From(QuantityValue value, MassUnit fromUnit) -#endif - { - return new Mass((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Mass)) throw new ArgumentException("Expected type Mass.", nameof(obj)); - - return CompareTo((Mass)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Mass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Mass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Mass)) - return false; - - var objQuantity = (Mass)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Mass by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Mass, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Mass other, Mass maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Mass. - public override int GetHashCode() - { - return new { type = typeof(Mass), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Mass to another Mass with the unit representation . - /// - /// A Mass with the specified unit. - public Mass ToUnit(MassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Mass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassUnit.Centigram: return (_value/1e3) * 1e-2d; - case MassUnit.Decagram: return (_value/1e3) * 1e1d; - case MassUnit.Decigram: return (_value/1e3) * 1e-1d; - case MassUnit.Gram: return _value/1e3; - case MassUnit.Hectogram: return (_value/1e3) * 1e2d; - case MassUnit.Kilogram: return (_value/1e3) * 1e3d; - case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; - case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; - case MassUnit.LongHundredweight: return _value/0.01968413055222121; - case MassUnit.LongTon: return _value*1.0160469088e3; - case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; - case MassUnit.Megatonne: return (_value*1e3) * 1e6d; - case MassUnit.Microgram: return (_value/1e3) * 1e-6d; - case MassUnit.Milligram: return (_value/1e3) * 1e-3d; - case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; - case MassUnit.Ounce: return _value/35.2739619; - case MassUnit.Pound: return _value*0.45359237; - case MassUnit.ShortHundredweight: return _value/0.022046226218487758; - case MassUnit.ShortTon: return _value*9.0718474e2; - case MassUnit.Slug: return _value/6.852176556196105e-2; - case MassUnit.Stone: return _value/0.1574731728702698; - case MassUnit.Tonne: return _value*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; - case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; - case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; - case MassUnit.Gram: return baseUnitValue*1e3; - case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; - case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; - case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; - case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; - case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; - case MassUnit.LongTon: return baseUnitValue/1.0160469088e3; - case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; - case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; - case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; - case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; - case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; - case MassUnit.Ounce: return baseUnitValue*35.2739619; - case MassUnit.Pound: return baseUnitValue/0.45359237; - case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; - case MassUnit.ShortTon: return baseUnitValue/9.0718474e2; - case MassUnit.Slug: return baseUnitValue*6.852176556196105e-2; - case MassUnit.Stone: return baseUnitValue*0.1574731728702698; - case MassUnit.Tonne: return baseUnitValue/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Mass Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Mass result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Kilogram - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MassUnit ToStringDefaultUnit { get; set; } = MassUnit.Kilogram; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Mass - /// - public static Mass MaxValue => new Mass(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Mass - /// - public static Mass MinValue => new Mass(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Mass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Mass.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs b/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs deleted file mode 100644 index d60a2c5d4a..0000000000 --- a/Common/GeneratedCode/Quantities/MassFlow.Common.g.cs +++ /dev/null @@ -1,847 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassFlow : IQuantity -#else - public partial struct MassFlow : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFlowUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassFlow() - { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit GramPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MassFlow(double gramspersecond) - { - _value = Convert.ToDouble(gramspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MassFlow(double numericValue, MassFlowUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit GramPerSecond. - /// - /// Value assuming base unit GramPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassFlow(long gramspersecond) : this(Convert.ToDouble(gramspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit GramPerSecond. - /// - /// Value assuming base unit GramPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassFlow(decimal gramspersecond) : this(Convert.ToDouble(gramspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassFlow; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassFlow quantity. - /// - public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); - - /// - /// Get MassFlow in CentigramsPerSecond. - /// - public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); - - /// - /// Get MassFlow in DecagramsPerSecond. - /// - public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); - - /// - /// Get MassFlow in DecigramsPerSecond. - /// - public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); - - /// - /// Get MassFlow in GramsPerSecond. - /// - public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); - - /// - /// Get MassFlow in HectogramsPerSecond. - /// - public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); - - /// - /// Get MassFlow in KilogramsPerHour. - /// - public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); - - /// - /// Get MassFlow in KilogramsPerMinute. - /// - public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); - - /// - /// Get MassFlow in KilogramsPerSecond. - /// - public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); - - /// - /// Get MassFlow in MegapoundsPerHour. - /// - public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); - - /// - /// Get MassFlow in MegapoundsPerMinute. - /// - public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); - - /// - /// Get MassFlow in MicrogramsPerSecond. - /// - public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); - - /// - /// Get MassFlow in MilligramsPerSecond. - /// - public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); - - /// - /// Get MassFlow in NanogramsPerSecond. - /// - public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); - - /// - /// Get MassFlow in PoundsPerHour. - /// - public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); - - /// - /// Get MassFlow in PoundsPerMinute. - /// - public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); - - /// - /// Get MassFlow in ShortTonsPerHour. - /// - public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); - - /// - /// Get MassFlow in TonnesPerDay. - /// - public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); - - /// - /// Get MassFlow in TonnesPerHour. - /// - public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. - /// - public static MassFlow Zero => new MassFlow(0, BaseUnit); - - /// - /// Get MassFlow from CentigramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromCentigramsPerSecond(double centigramspersecond) -#else - public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) -#endif - { - double value = (double) centigramspersecond; - return new MassFlow(value, MassFlowUnit.CentigramPerSecond); - } - - /// - /// Get MassFlow from DecagramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecagramsPerSecond(double decagramspersecond) -#else - public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) -#endif - { - double value = (double) decagramspersecond; - return new MassFlow(value, MassFlowUnit.DecagramPerSecond); - } - - /// - /// Get MassFlow from DecigramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecigramsPerSecond(double decigramspersecond) -#else - public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) -#endif - { - double value = (double) decigramspersecond; - return new MassFlow(value, MassFlowUnit.DecigramPerSecond); - } - - /// - /// Get MassFlow from GramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromGramsPerSecond(double gramspersecond) -#else - public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) -#endif - { - double value = (double) gramspersecond; - return new MassFlow(value, MassFlowUnit.GramPerSecond); - } - - /// - /// Get MassFlow from HectogramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) -#else - public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) -#endif - { - double value = (double) hectogramspersecond; - return new MassFlow(value, MassFlowUnit.HectogramPerSecond); - } - - /// - /// Get MassFlow from KilogramsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerHour(double kilogramsperhour) -#else - public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) -#endif - { - double value = (double) kilogramsperhour; - return new MassFlow(value, MassFlowUnit.KilogramPerHour); - } - - /// - /// Get MassFlow from KilogramsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerMinute(double kilogramsperminute) -#else - public static MassFlow FromKilogramsPerMinute(QuantityValue kilogramsperminute) -#endif - { - double value = (double) kilogramsperminute; - return new MassFlow(value, MassFlowUnit.KilogramPerMinute); - } - - /// - /// Get MassFlow from KilogramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) -#else - public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) -#endif - { - double value = (double) kilogramspersecond; - return new MassFlow(value, MassFlowUnit.KilogramPerSecond); - } - - /// - /// Get MassFlow from MegapoundsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) -#else - public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) -#endif - { - double value = (double) megapoundsperhour; - return new MassFlow(value, MassFlowUnit.MegapoundPerHour); - } - - /// - /// Get MassFlow from MegapoundsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerMinute(double megapoundsperminute) -#else - public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute) -#endif - { - double value = (double) megapoundsperminute; - return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); - } - - /// - /// Get MassFlow from MicrogramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) -#else - public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) -#endif - { - double value = (double) microgramspersecond; - return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); - } - - /// - /// Get MassFlow from MilligramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMilligramsPerSecond(double milligramspersecond) -#else - public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) -#endif - { - double value = (double) milligramspersecond; - return new MassFlow(value, MassFlowUnit.MilligramPerSecond); - } - - /// - /// Get MassFlow from NanogramsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) -#else - public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) -#endif - { - double value = (double) nanogramspersecond; - return new MassFlow(value, MassFlowUnit.NanogramPerSecond); - } - - /// - /// Get MassFlow from PoundsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerHour(double poundsperhour) -#else - public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) -#endif - { - double value = (double) poundsperhour; - return new MassFlow(value, MassFlowUnit.PoundPerHour); - } - - /// - /// Get MassFlow from PoundsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerMinute(double poundsperminute) -#else - public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) -#endif - { - double value = (double) poundsperminute; - return new MassFlow(value, MassFlowUnit.PoundPerMinute); - } - - /// - /// Get MassFlow from ShortTonsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromShortTonsPerHour(double shorttonsperhour) -#else - public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) -#endif - { - double value = (double) shorttonsperhour; - return new MassFlow(value, MassFlowUnit.ShortTonPerHour); - } - - /// - /// Get MassFlow from TonnesPerDay. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerDay(double tonnesperday) -#else - public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) -#endif - { - double value = (double) tonnesperday; - return new MassFlow(value, MassFlowUnit.TonnePerDay); - } - - /// - /// Get MassFlow from TonnesPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerHour(double tonnesperhour) -#else - public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) -#endif - { - double value = (double) tonnesperhour; - return new MassFlow(value, MassFlowUnit.TonnePerHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlow unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlow From(double value, MassFlowUnit fromUnit) -#else - public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) -#endif - { - return new MassFlow((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassFlow)) throw new ArgumentException("Expected type MassFlow.", nameof(obj)); - - return CompareTo((MassFlow)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MassFlow)) - return false; - - var objQuantity = (MassFlow)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MassFlow by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MassFlow, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MassFlow other, MassFlow maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlow. - public override int GetHashCode() - { - return new { type = typeof(MassFlow), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFlowUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlow to another MassFlow with the unit representation . - /// - /// A MassFlow with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; - case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; - case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; - case MassFlowUnit.GramPerSecond: return _value; - case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; - case MassFlowUnit.KilogramPerHour: return _value/3.6; - case MassFlowUnit.KilogramPerMinute: return _value/0.06; - case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; - case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (_value/0.132277) * 1e6d; - case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; - case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; - case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; - case MassFlowUnit.PoundPerHour: return _value/7.93664; - case MassFlowUnit.PoundPerMinute: return _value/0.132277; - case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; - case MassFlowUnit.TonnePerDay: return _value/0.0864000; - case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFlowUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; - case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; - case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; - case MassFlowUnit.GramPerSecond: return baseUnitValue; - case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; - case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; - case MassFlowUnit.KilogramPerMinute: return baseUnitValue*0.06; - case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; - case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (baseUnitValue*0.132277) / 1e6d; - case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; - case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; - case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; - case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; - case MassFlowUnit.PoundPerMinute: return baseUnitValue*0.132277; - case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; - case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; - case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlow result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFlowUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is GramPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MassFlowUnit ToStringDefaultUnit { get; set; } = MassFlowUnit.GramPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassFlowUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassFlow - /// - public static MassFlow MaxValue => new MassFlow(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassFlow - /// - public static MassFlow MinValue => new MassFlow(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlow.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs b/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs deleted file mode 100644 index 3b11775e10..0000000000 --- a/Common/GeneratedCode/Quantities/MassFlux.Common.g.cs +++ /dev/null @@ -1,511 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flux is the mass flow rate per unit area. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassFlux : IQuantity -#else - public partial struct MassFlux : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFluxUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassFlux() - { - BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerSecondPerSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MassFlux(double kilogramspersecondpersquaremeter) - { - _value = Convert.ToDouble(kilogramspersecondpersquaremeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MassFlux(double numericValue, MassFluxUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerSecondPerSquareMeter. - /// - /// Value assuming base unit KilogramPerSecondPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassFlux(long kilogramspersecondpersquaremeter) : this(Convert.ToDouble(kilogramspersecondpersquaremeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerSecondPerSquareMeter. - /// - /// Value assuming base unit KilogramPerSecondPerSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassFlux(decimal kilogramspersecondpersquaremeter) : this(Convert.ToDouble(kilogramspersecondpersquaremeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassFlux; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassFlux quantity. - /// - public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); - - /// - /// Get MassFlux in GramsPerSecondPerSquareMeter. - /// - public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); - - /// - /// Get MassFlux in KilogramsPerSecondPerSquareMeter. - /// - public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. - /// - public static MassFlux Zero => new MassFlux(0, BaseUnit); - - /// - /// Get MassFlux from GramsPerSecondPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) -#else - public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) -#endif - { - double value = (double) gramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); - } - - /// - /// Get MassFlux from KilogramsPerSecondPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) -#else - public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) -#endif - { - double value = (double) kilogramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlux unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlux From(double value, MassFluxUnit fromUnit) -#else - public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) -#endif - { - return new MassFlux((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassFlux)) throw new ArgumentException("Expected type MassFlux.", nameof(obj)); - - return CompareTo((MassFlux)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MassFlux)) - return false; - - var objQuantity = (MassFlux)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MassFlux by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MassFlux, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MassFlux other, MassFlux maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlux. - public override int GetHashCode() - { - return new { type = typeof(MassFlux), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFluxUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlux to another MassFlux with the unit representation . - /// - /// A MassFlux with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFluxUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFluxUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerSecondPerSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MassFluxUnit ToStringDefaultUnit { get; set; } = MassFluxUnit.KilogramPerSecondPerSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassFluxUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassFlux - /// - public static MassFlux MaxValue => new MassFlux(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassFlux - /// - public static MassFlux MinValue => new MassFlux(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlux.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs b/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs deleted file mode 100644 index 73d79c6d4d..0000000000 --- a/Common/GeneratedCode/Quantities/MassMomentOfInertia.Common.g.cs +++ /dev/null @@ -1,1057 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A property of body reflects how its mass is distributed with regard to an axis. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MassMomentOfInertia : IQuantity -#else - public partial struct MassMomentOfInertia : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassMomentOfInertiaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MassMomentOfInertia() - { - BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramSquareMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MassMomentOfInertia(double kilogramsquaremeters) - { - _value = Convert.ToDouble(kilogramsquaremeters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MassMomentOfInertia(double numericValue, MassMomentOfInertiaUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramSquareMeter. - /// - /// Value assuming base unit KilogramSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassMomentOfInertia(long kilogramsquaremeters) : this(Convert.ToDouble(kilogramsquaremeters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramSquareMeter. - /// - /// Value assuming base unit KilogramSquareMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MassMomentOfInertia(decimal kilogramsquaremeters) : this(Convert.ToDouble(kilogramsquaremeters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MassMomentOfInertia; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MassMomentOfInertia quantity. - /// - public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); - - /// - /// Get MassMomentOfInertia in GramSquareCentimeters. - /// - public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in GramSquareDecimeters. - /// - public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in GramSquareMeters. - /// - public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); - - /// - /// Get MassMomentOfInertia in GramSquareMillimeters. - /// - public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareCentimeters. - /// - public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareDecimeters. - /// - public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareMeters. - /// - public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); - - /// - /// Get MassMomentOfInertia in KilogramSquareMillimeters. - /// - public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareCentimeters. - /// - public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareDecimeters. - /// - public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareMeters. - /// - public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); - - /// - /// Get MassMomentOfInertia in KilotonneSquareMilimeters. - /// - public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareCentimeters. - /// - public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareDecimeters. - /// - public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareMeters. - /// - public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); - - /// - /// Get MassMomentOfInertia in MegatonneSquareMilimeters. - /// - public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareCentimeters. - /// - public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareDecimeters. - /// - public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareMeters. - /// - public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); - - /// - /// Get MassMomentOfInertia in MilligramSquareMillimeters. - /// - public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); - - /// - /// Get MassMomentOfInertia in PoundSquareFeet. - /// - public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); - - /// - /// Get MassMomentOfInertia in PoundSquareInches. - /// - public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); - - /// - /// Get MassMomentOfInertia in SlugSquareFeet. - /// - public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); - - /// - /// Get MassMomentOfInertia in SlugSquareInches. - /// - public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); - - /// - /// Get MassMomentOfInertia in TonneSquareCentimeters. - /// - public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); - - /// - /// Get MassMomentOfInertia in TonneSquareDecimeters. - /// - public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); - - /// - /// Get MassMomentOfInertia in TonneSquareMeters. - /// - public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); - - /// - /// Get MassMomentOfInertia in TonneSquareMilimeters. - /// - public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. - /// - public static MassMomentOfInertia Zero => new MassMomentOfInertia(0, BaseUnit); - - /// - /// Get MassMomentOfInertia from GramSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) -#else - public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) -#endif - { - double value = (double) gramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) -#else - public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) -#endif - { - double value = (double) gramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) -#else - public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) -#endif - { - double value = (double) gramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from GramSquareMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) -#else - public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) -#endif - { - double value = (double) gramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) -#else - public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) -#endif - { - double value = (double) kilogramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) -#else - public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) -#endif - { - double value = (double) kilogramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) -#else - public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) -#endif - { - double value = (double) kilogramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from KilogramSquareMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) -#else - public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) -#endif - { - double value = (double) kilogramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) -#endif - { - double value = (double) kilotonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) -#endif - { - double value = (double) kilotonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) -#else - public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) -#endif - { - double value = (double) kilotonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from KilotonneSquareMilimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) -#else - public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) -#endif - { - double value = (double) kilotonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) -#endif - { - double value = (double) megatonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) -#endif - { - double value = (double) megatonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) -#else - public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) -#endif - { - double value = (double) megatonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from MegatonneSquareMilimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) -#else - public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) -#endif - { - double value = (double) megatonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) -#else - public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) -#endif - { - double value = (double) milligramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) -#else - public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) -#endif - { - double value = (double) milligramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) -#else - public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) -#endif - { - double value = (double) milligramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); - } - - /// - /// Get MassMomentOfInertia from MilligramSquareMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) -#else - public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) -#endif - { - double value = (double) milligramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); - } - - /// - /// Get MassMomentOfInertia from PoundSquareFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) -#else - public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) -#endif - { - double value = (double) poundsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); - } - - /// - /// Get MassMomentOfInertia from PoundSquareInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) -#else - public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) -#endif - { - double value = (double) poundsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); - } - - /// - /// Get MassMomentOfInertia from SlugSquareFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareFeet(double slugsquarefeet) -#else - public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) -#endif - { - double value = (double) slugsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); - } - - /// - /// Get MassMomentOfInertia from SlugSquareInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareInches(double slugsquareinches) -#else - public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) -#endif - { - double value = (double) slugsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); - } - - /// - /// Get MassMomentOfInertia from TonneSquareCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) -#else - public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) -#endif - { - double value = (double) tonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) -#else - public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) -#endif - { - double value = (double) tonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) -#else - public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) -#endif - { - double value = (double) tonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); - } - - /// - /// Get MassMomentOfInertia from TonneSquareMilimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) -#else - public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) -#endif - { - double value = (double) tonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassMomentOfInertia unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) -#else - public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) -#endif - { - return new MassMomentOfInertia((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MassMomentOfInertia)) throw new ArgumentException("Expected type MassMomentOfInertia.", nameof(obj)); - - return CompareTo((MassMomentOfInertia)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MassMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MassMomentOfInertia)) - return false; - - var objQuantity = (MassMomentOfInertia)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MassMomentOfInertia by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MassMomentOfInertia, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MassMomentOfInertia other, MassMomentOfInertia maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassMomentOfInertia. - public override int GetHashCode() - { - return new { type = typeof(MassMomentOfInertia), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . - /// - /// A MassMomentOfInertia with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return _value/1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return _value/1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return _value/1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return _value/1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (_value/1e7) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (_value/1e5) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (_value/1e9) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (_value/1e1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (_value/1e-1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (_value/1e-3) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (_value/1e3) * 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (_value/1e1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (_value/1e-1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (_value/1e-3) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (_value/1e3) * 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (_value/1e7) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (_value/1e5) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (_value/1e3) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (_value/1e9) * 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return _value*4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return _value*2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return _value*1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return _value*9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return _value/1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return _value/1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return _value/1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return _value/1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassMomentOfInertiaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return baseUnitValue*1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return baseUnitValue*1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return baseUnitValue*1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return baseUnitValue*1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (baseUnitValue*1e7) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (baseUnitValue*1e5) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (baseUnitValue*1e9) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (baseUnitValue*1e1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (baseUnitValue*1e-3) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (baseUnitValue*1e3) / 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (baseUnitValue*1e1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (baseUnitValue*1e-3) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (baseUnitValue*1e3) / 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (baseUnitValue*1e7) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (baseUnitValue*1e5) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (baseUnitValue*1e3) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (baseUnitValue*1e9) / 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return baseUnitValue/4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return baseUnitValue/2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return baseUnitValue/1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return baseUnitValue/9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return baseUnitValue*1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return baseUnitValue*1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return baseUnitValue*1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return baseUnitValue*1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassMomentOfInertia Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramSquareMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MassMomentOfInertiaUnit ToStringDefaultUnit { get; set; } = MassMomentOfInertiaUnit.KilogramSquareMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MassMomentOfInertiaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MaxValue => new MassMomentOfInertia(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MinValue => new MassMomentOfInertia(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MassMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs deleted file mode 100644 index 37f4cefa41..0000000000 --- a/Common/GeneratedCode/Quantities/MolarEnergy.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar energy is the amount of energy stored in 1 mole of a substance. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarEnergy : IQuantity -#else - public partial struct MolarEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerMole. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MolarEnergy(double joulespermole) - { - _value = Convert.ToDouble(joulespermole); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MolarEnergy(double numericValue, MolarEnergyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerMole. - /// - /// Value assuming base unit JoulePerMole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarEnergy(long joulespermole) : this(Convert.ToDouble(joulespermole), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerMole. - /// - /// Value assuming base unit JoulePerMole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarEnergy(decimal joulespermole) : this(Convert.ToDouble(joulespermole), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarEnergy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarEnergy quantity. - /// - public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); - - /// - /// Get MolarEnergy in JoulesPerMole. - /// - public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); - - /// - /// Get MolarEnergy in KilojoulesPerMole. - /// - public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); - - /// - /// Get MolarEnergy in MegajoulesPerMole. - /// - public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. - /// - public static MolarEnergy Zero => new MolarEnergy(0, BaseUnit); - - /// - /// Get MolarEnergy from JoulesPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromJoulesPerMole(double joulespermole) -#else - public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) -#endif - { - double value = (double) joulespermole; - return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); - } - - /// - /// Get MolarEnergy from KilojoulesPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) -#else - public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) -#endif - { - double value = (double) kilojoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); - } - - /// - /// Get MolarEnergy from MegajoulesPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) -#else - public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) -#endif - { - double value = (double) megajoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) -#else - public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) -#endif - { - return new MolarEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarEnergy)) throw new ArgumentException("Expected type MolarEnergy.", nameof(obj)); - - return CompareTo((MolarEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MolarEnergy)) - return false; - - var objQuantity = (MolarEnergy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MolarEnergy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MolarEnergy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MolarEnergy other, MolarEnergy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEnergy. - public override int GetHashCode() - { - return new { type = typeof(MolarEnergy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEnergy to another MolarEnergy with the unit representation . - /// - /// A MolarEnergy with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarEnergyUnit.JoulePerMole: return _value; - case MolarEnergyUnit.KilojoulePerMole: return (_value) * 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEnergyUnit.JoulePerMole: return baseUnitValue; - case MolarEnergyUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerMole - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MolarEnergyUnit ToStringDefaultUnit { get; set; } = MolarEnergyUnit.JoulePerMole; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarEnergy - /// - public static MolarEnergy MaxValue => new MolarEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarEnergy - /// - public static MolarEnergy MinValue => new MolarEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs b/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs deleted file mode 100644 index e39453521e..0000000000 --- a/Common/GeneratedCode/Quantities/MolarEntropy.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarEntropy : IQuantity -#else - public partial struct MolarEntropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarEntropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerMoleKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MolarEntropy(double joulespermolekelvin) - { - _value = Convert.ToDouble(joulespermolekelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MolarEntropy(double numericValue, MolarEntropyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerMoleKelvin. - /// - /// Value assuming base unit JoulePerMoleKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarEntropy(long joulespermolekelvin) : this(Convert.ToDouble(joulespermolekelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerMoleKelvin. - /// - /// Value assuming base unit JoulePerMoleKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarEntropy(decimal joulespermolekelvin) : this(Convert.ToDouble(joulespermolekelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarEntropy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarEntropy quantity. - /// - public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); - - /// - /// Get MolarEntropy in JoulesPerMoleKelvin. - /// - public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); - - /// - /// Get MolarEntropy in KilojoulesPerMoleKelvin. - /// - public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); - - /// - /// Get MolarEntropy in MegajoulesPerMoleKelvin. - /// - public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. - /// - public static MolarEntropy Zero => new MolarEntropy(0, BaseUnit); - - /// - /// Get MolarEntropy from JoulesPerMoleKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) -#else - public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) -#endif - { - double value = (double) joulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); - } - - /// - /// Get MolarEntropy from KilojoulesPerMoleKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) -#else - public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) -#endif - { - double value = (double) kilojoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); - } - - /// - /// Get MolarEntropy from MegajoulesPerMoleKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) -#else - public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) -#endif - { - double value = (double) megajoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEntropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) -#else - public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) -#endif - { - return new MolarEntropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarEntropy)) throw new ArgumentException("Expected type MolarEntropy.", nameof(obj)); - - return CompareTo((MolarEntropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MolarEntropy)) - return false; - - var objQuantity = (MolarEntropy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MolarEntropy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MolarEntropy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MolarEntropy other, MolarEntropy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEntropy. - public override int GetHashCode() - { - return new { type = typeof(MolarEntropy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEntropy to another MolarEntropy with the unit representation . - /// - /// A MolarEntropy with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return _value; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (_value) * 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return baseUnitValue; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (baseUnitValue) / 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEntropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEntropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEntropyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerMoleKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MolarEntropyUnit ToStringDefaultUnit { get; set; } = MolarEntropyUnit.JoulePerMoleKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarEntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarEntropy - /// - public static MolarEntropy MaxValue => new MolarEntropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarEntropy - /// - public static MolarEntropy MinValue => new MolarEntropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs b/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs deleted file mode 100644 index 4ff7707aa2..0000000000 --- a/Common/GeneratedCode/Quantities/MolarMass.Common.g.cs +++ /dev/null @@ -1,721 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class MolarMass : IQuantity -#else - public partial struct MolarMass : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarMassUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static MolarMass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); - } - - /// - /// Creates the quantity with the given value in the base unit KilogramPerMole. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public MolarMass(double kilogramspermole) - { - _value = Convert.ToDouble(kilogramspermole); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - MolarMass(double numericValue, MolarMassUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerMole. - /// - /// Value assuming base unit KilogramPerMole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarMass(long kilogramspermole) : this(Convert.ToDouble(kilogramspermole), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit KilogramPerMole. - /// - /// Value assuming base unit KilogramPerMole. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - MolarMass(decimal kilogramspermole) : this(Convert.ToDouble(kilogramspermole), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.MolarMass; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the MolarMass quantity. - /// - public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); - - /// - /// Get MolarMass in CentigramsPerMole. - /// - public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); - - /// - /// Get MolarMass in DecagramsPerMole. - /// - public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); - - /// - /// Get MolarMass in DecigramsPerMole. - /// - public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); - - /// - /// Get MolarMass in GramsPerMole. - /// - public double GramsPerMole => As(MolarMassUnit.GramPerMole); - - /// - /// Get MolarMass in HectogramsPerMole. - /// - public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); - - /// - /// Get MolarMass in KilogramsPerMole. - /// - public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); - - /// - /// Get MolarMass in KilopoundsPerMole. - /// - public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); - - /// - /// Get MolarMass in MegapoundsPerMole. - /// - public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); - - /// - /// Get MolarMass in MicrogramsPerMole. - /// - public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); - - /// - /// Get MolarMass in MilligramsPerMole. - /// - public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); - - /// - /// Get MolarMass in NanogramsPerMole. - /// - public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); - - /// - /// Get MolarMass in PoundsPerMole. - /// - public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. - /// - public static MolarMass Zero => new MolarMass(0, BaseUnit); - - /// - /// Get MolarMass from CentigramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromCentigramsPerMole(double centigramspermole) -#else - public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) -#endif - { - double value = (double) centigramspermole; - return new MolarMass(value, MolarMassUnit.CentigramPerMole); - } - - /// - /// Get MolarMass from DecagramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecagramsPerMole(double decagramspermole) -#else - public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) -#endif - { - double value = (double) decagramspermole; - return new MolarMass(value, MolarMassUnit.DecagramPerMole); - } - - /// - /// Get MolarMass from DecigramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecigramsPerMole(double decigramspermole) -#else - public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) -#endif - { - double value = (double) decigramspermole; - return new MolarMass(value, MolarMassUnit.DecigramPerMole); - } - - /// - /// Get MolarMass from GramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromGramsPerMole(double gramspermole) -#else - public static MolarMass FromGramsPerMole(QuantityValue gramspermole) -#endif - { - double value = (double) gramspermole; - return new MolarMass(value, MolarMassUnit.GramPerMole); - } - - /// - /// Get MolarMass from HectogramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromHectogramsPerMole(double hectogramspermole) -#else - public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) -#endif - { - double value = (double) hectogramspermole; - return new MolarMass(value, MolarMassUnit.HectogramPerMole); - } - - /// - /// Get MolarMass from KilogramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilogramsPerMole(double kilogramspermole) -#else - public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) -#endif - { - double value = (double) kilogramspermole; - return new MolarMass(value, MolarMassUnit.KilogramPerMole); - } - - /// - /// Get MolarMass from KilopoundsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) -#else - public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) -#endif - { - double value = (double) kilopoundspermole; - return new MolarMass(value, MolarMassUnit.KilopoundPerMole); - } - - /// - /// Get MolarMass from MegapoundsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMegapoundsPerMole(double megapoundspermole) -#else - public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) -#endif - { - double value = (double) megapoundspermole; - return new MolarMass(value, MolarMassUnit.MegapoundPerMole); - } - - /// - /// Get MolarMass from MicrogramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMicrogramsPerMole(double microgramspermole) -#else - public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) -#endif - { - double value = (double) microgramspermole; - return new MolarMass(value, MolarMassUnit.MicrogramPerMole); - } - - /// - /// Get MolarMass from MilligramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMilligramsPerMole(double milligramspermole) -#else - public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) -#endif - { - double value = (double) milligramspermole; - return new MolarMass(value, MolarMassUnit.MilligramPerMole); - } - - /// - /// Get MolarMass from NanogramsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromNanogramsPerMole(double nanogramspermole) -#else - public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) -#endif - { - double value = (double) nanogramspermole; - return new MolarMass(value, MolarMassUnit.NanogramPerMole); - } - - /// - /// Get MolarMass from PoundsPerMole. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromPoundsPerMole(double poundspermole) -#else - public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) -#endif - { - double value = (double) poundspermole; - return new MolarMass(value, MolarMassUnit.PoundPerMole); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarMass unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarMass From(double value, MolarMassUnit fromUnit) -#else - public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) -#endif - { - return new MolarMass((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarMassUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is MolarMass)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); - - return CompareTo((MolarMass)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(MolarMass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarMass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is MolarMass)) - return false; - - var objQuantity = (MolarMass)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another MolarMass by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(MolarMass, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(MolarMass other, MolarMass maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarMass. - public override int GetHashCode() - { - return new { type = typeof(MolarMass), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarMassUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarMass to another MolarMass with the unit representation . - /// - /// A MolarMass with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarMass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarMassUnit.CentigramPerMole: return (_value/1e3) * 1e-2d; - case MolarMassUnit.DecagramPerMole: return (_value/1e3) * 1e1d; - case MolarMassUnit.DecigramPerMole: return (_value/1e3) * 1e-1d; - case MolarMassUnit.GramPerMole: return _value/1e3; - case MolarMassUnit.HectogramPerMole: return (_value/1e3) * 1e2d; - case MolarMassUnit.KilogramPerMole: return (_value/1e3) * 1e3d; - case MolarMassUnit.KilopoundPerMole: return (_value*0.45359237) * 1e3d; - case MolarMassUnit.MegapoundPerMole: return (_value*0.45359237) * 1e6d; - case MolarMassUnit.MicrogramPerMole: return (_value/1e3) * 1e-6d; - case MolarMassUnit.MilligramPerMole: return (_value/1e3) * 1e-3d; - case MolarMassUnit.NanogramPerMole: return (_value/1e3) * 1e-9d; - case MolarMassUnit.PoundPerMole: return _value*0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarMassUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarMassUnit.CentigramPerMole: return (baseUnitValue*1e3) / 1e-2d; - case MolarMassUnit.DecagramPerMole: return (baseUnitValue*1e3) / 1e1d; - case MolarMassUnit.DecigramPerMole: return (baseUnitValue*1e3) / 1e-1d; - case MolarMassUnit.GramPerMole: return baseUnitValue*1e3; - case MolarMassUnit.HectogramPerMole: return (baseUnitValue*1e3) / 1e2d; - case MolarMassUnit.KilogramPerMole: return (baseUnitValue*1e3) / 1e3d; - case MolarMassUnit.KilopoundPerMole: return (baseUnitValue/0.45359237) / 1e3d; - case MolarMassUnit.MegapoundPerMole: return (baseUnitValue/0.45359237) / 1e6d; - case MolarMassUnit.MicrogramPerMole: return (baseUnitValue*1e3) / 1e-6d; - case MolarMassUnit.MilligramPerMole: return (baseUnitValue*1e3) / 1e-3d; - case MolarMassUnit.NanogramPerMole: return (baseUnitValue*1e3) / 1e-9d; - case MolarMassUnit.PoundPerMole: return baseUnitValue/0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarMass Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarMass result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarMassUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is KilogramPerMole - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MolarMassUnit ToStringDefaultUnit { get; set; } = MolarMassUnit.KilogramPerMole; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarMassUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of MolarMass - /// - public static MolarMass MaxValue => new MolarMass(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of MolarMass - /// - public static MolarMass MinValue => new MolarMass(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => MolarMass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarMass.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Molarity.Common.g.cs b/Common/GeneratedCode/Quantities/Molarity.Common.g.cs deleted file mode 100644 index c8a35c446e..0000000000 --- a/Common/GeneratedCode/Quantities/Molarity.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Molarity : IQuantity -#else - public partial struct Molarity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Molarity() - { - BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); - } - - /// - /// Creates the quantity with the given value in the base unit MolesPerCubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Molarity(double molespercubicmeter) - { - _value = Convert.ToDouble(molespercubicmeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Molarity(double numericValue, MolarityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit MolesPerCubicMeter. - /// - /// Value assuming base unit MolesPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Molarity(long molespercubicmeter) : this(Convert.ToDouble(molespercubicmeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit MolesPerCubicMeter. - /// - /// Value assuming base unit MolesPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Molarity(decimal molespercubicmeter) : this(Convert.ToDouble(molespercubicmeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Molarity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Molarity quantity. - /// - public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); - - /// - /// Get Molarity in CentimolesPerLiter. - /// - public double CentimolesPerLiter => As(MolarityUnit.CentimolesPerLiter); - - /// - /// Get Molarity in DecimolesPerLiter. - /// - public double DecimolesPerLiter => As(MolarityUnit.DecimolesPerLiter); - - /// - /// Get Molarity in MicromolesPerLiter. - /// - public double MicromolesPerLiter => As(MolarityUnit.MicromolesPerLiter); - - /// - /// Get Molarity in MillimolesPerLiter. - /// - public double MillimolesPerLiter => As(MolarityUnit.MillimolesPerLiter); - - /// - /// Get Molarity in MolesPerCubicMeter. - /// - public double MolesPerCubicMeter => As(MolarityUnit.MolesPerCubicMeter); - - /// - /// Get Molarity in MolesPerLiter. - /// - public double MolesPerLiter => As(MolarityUnit.MolesPerLiter); - - /// - /// Get Molarity in NanomolesPerLiter. - /// - public double NanomolesPerLiter => As(MolarityUnit.NanomolesPerLiter); - - /// - /// Get Molarity in PicomolesPerLiter. - /// - public double PicomolesPerLiter => As(MolarityUnit.PicomolesPerLiter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. - /// - public static Molarity Zero => new Molarity(0, BaseUnit); - - /// - /// Get Molarity from CentimolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromCentimolesPerLiter(double centimolesperliter) -#else - public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) -#endif - { - double value = (double) centimolesperliter; - return new Molarity(value, MolarityUnit.CentimolesPerLiter); - } - - /// - /// Get Molarity from DecimolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromDecimolesPerLiter(double decimolesperliter) -#else - public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) -#endif - { - double value = (double) decimolesperliter; - return new Molarity(value, MolarityUnit.DecimolesPerLiter); - } - - /// - /// Get Molarity from MicromolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMicromolesPerLiter(double micromolesperliter) -#else - public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) -#endif - { - double value = (double) micromolesperliter; - return new Molarity(value, MolarityUnit.MicromolesPerLiter); - } - - /// - /// Get Molarity from MillimolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMillimolesPerLiter(double millimolesperliter) -#else - public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) -#endif - { - double value = (double) millimolesperliter; - return new Molarity(value, MolarityUnit.MillimolesPerLiter); - } - - /// - /// Get Molarity from MolesPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) -#else - public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) -#endif - { - double value = (double) molespercubicmeter; - return new Molarity(value, MolarityUnit.MolesPerCubicMeter); - } - - /// - /// Get Molarity from MolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerLiter(double molesperliter) -#else - public static Molarity FromMolesPerLiter(QuantityValue molesperliter) -#endif - { - double value = (double) molesperliter; - return new Molarity(value, MolarityUnit.MolesPerLiter); - } - - /// - /// Get Molarity from NanomolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromNanomolesPerLiter(double nanomolesperliter) -#else - public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) -#endif - { - double value = (double) nanomolesperliter; - return new Molarity(value, MolarityUnit.NanomolesPerLiter); - } - - /// - /// Get Molarity from PicomolesPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromPicomolesPerLiter(double picomolesperliter) -#else - public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) -#endif - { - double value = (double) picomolesperliter; - return new Molarity(value, MolarityUnit.PicomolesPerLiter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Molarity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Molarity From(double value, MolarityUnit fromUnit) -#else - public static Molarity From(QuantityValue value, MolarityUnit fromUnit) -#endif - { - return new Molarity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Molarity)) throw new ArgumentException("Expected type Molarity.", nameof(obj)); - - return CompareTo((Molarity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Molarity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Molarity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Molarity)) - return false; - - var objQuantity = (Molarity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Molarity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Molarity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Molarity other, Molarity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Molarity. - public override int GetHashCode() - { - return new { type = typeof(Molarity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Molarity to another Molarity with the unit representation . - /// - /// A Molarity with the specified unit. - public Molarity ToUnit(MolarityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Molarity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return _value; - case MolarityUnit.MolesPerLiter: return _value/1e-3; - case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; - case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; - case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; - case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; - case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; - case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; - case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; - case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Molarity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Molarity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is MolesPerCubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static MolarityUnit ToStringDefaultUnit { get; set; } = MolarityUnit.MolesPerCubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(MolarityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Molarity - /// - public static Molarity MaxValue => new Molarity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Molarity - /// - public static Molarity MinValue => new Molarity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Molarity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Molarity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Permeability.Common.g.cs b/Common/GeneratedCode/Quantities/Permeability.Common.g.cs deleted file mode 100644 index c49a813a9b..0000000000 --- a/Common/GeneratedCode/Quantities/Permeability.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Permeability : IQuantity -#else - public partial struct Permeability : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermeabilityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Permeability() - { - BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit HenryPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Permeability(double henriespermeter) - { - _value = Convert.ToDouble(henriespermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Permeability(double numericValue, PermeabilityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit HenryPerMeter. - /// - /// Value assuming base unit HenryPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Permeability(long henriespermeter) : this(Convert.ToDouble(henriespermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit HenryPerMeter. - /// - /// Value assuming base unit HenryPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Permeability(decimal henriespermeter) : this(Convert.ToDouble(henriespermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Permeability; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Permeability quantity. - /// - public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); - - /// - /// Get Permeability in HenriesPerMeter. - /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. - /// - public static Permeability Zero => new Permeability(0, BaseUnit); - - /// - /// Get Permeability from HenriesPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Permeability FromHenriesPerMeter(double henriespermeter) -#else - public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) -#endif - { - double value = (double) henriespermeter; - return new Permeability(value, PermeabilityUnit.HenryPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permeability unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permeability From(double value, PermeabilityUnit fromUnit) -#else - public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) -#endif - { - return new Permeability((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermeabilityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Permeability)) throw new ArgumentException("Expected type Permeability.", nameof(obj)); - - return CompareTo((Permeability)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Permeability other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permeability, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Permeability)) - return false; - - var objQuantity = (Permeability)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Permeability by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Permeability, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Permeability other, Permeability maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permeability. - public override int GetHashCode() - { - return new { type = typeof(Permeability), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permeability to another Permeability with the unit representation . - /// - /// A Permeability with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permeability(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PermeabilityUnit.HenryPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermeabilityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermeabilityUnit.HenryPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permeability Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permeability result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermeabilityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is HenryPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PermeabilityUnit ToStringDefaultUnit { get; set; } = PermeabilityUnit.HenryPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PermeabilityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Permeability - /// - public static Permeability MaxValue => new Permeability(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Permeability - /// - public static Permeability MinValue => new Permeability(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Permeability.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permeability.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs b/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs deleted file mode 100644 index 7df7c4a6a4..0000000000 --- a/Common/GeneratedCode/Quantities/Permittivity.Common.g.cs +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Permittivity : IQuantity -#else - public partial struct Permittivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermittivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Permittivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit FaradPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Permittivity(double faradspermeter) - { - _value = Convert.ToDouble(faradspermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Permittivity(double numericValue, PermittivityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit FaradPerMeter. - /// - /// Value assuming base unit FaradPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Permittivity(long faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit FaradPerMeter. - /// - /// Value assuming base unit FaradPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Permittivity(decimal faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Permittivity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Permittivity quantity. - /// - public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); - - /// - /// Get Permittivity in FaradsPerMeter. - /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. - /// - public static Permittivity Zero => new Permittivity(0, BaseUnit); - - /// - /// Get Permittivity from FaradsPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Permittivity FromFaradsPerMeter(double faradspermeter) -#else - public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) -#endif - { - double value = (double) faradspermeter; - return new Permittivity(value, PermittivityUnit.FaradPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permittivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permittivity From(double value, PermittivityUnit fromUnit) -#else - public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) -#endif - { - return new Permittivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermittivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Permittivity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj)); - - return CompareTo((Permittivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Permittivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permittivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Permittivity)) - return false; - - var objQuantity = (Permittivity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Permittivity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Permittivity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Permittivity other, Permittivity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permittivity. - public override int GetHashCode() - { - return new { type = typeof(Permittivity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermittivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permittivity to another Permittivity with the unit representation . - /// - /// A Permittivity with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permittivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PermittivityUnit.FaradPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermittivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermittivityUnit.FaradPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permittivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permittivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermittivityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is FaradPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PermittivityUnit ToStringDefaultUnit { get; set; } = PermittivityUnit.FaradPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PermittivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Permittivity - /// - public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Permittivity - /// - public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Permittivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permittivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Power.Common.g.cs b/Common/GeneratedCode/Quantities/Power.Common.g.cs deleted file mode 100644 index 146d3f210b..0000000000 --- a/Common/GeneratedCode/Quantities/Power.Common.g.cs +++ /dev/null @@ -1,888 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Power : IQuantity -#else - public partial struct Power : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Power() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Watt. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Power(double watts) - { - _value = Convert.ToDecimal(watts); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Power(decimal numericValue, PowerUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Watt. - /// - /// Value assuming base unit Watt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Power(long watts) : this(Convert.ToDecimal(watts), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Watt. - /// - /// Value assuming base unit Watt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Power(decimal watts) : this(Convert.ToDecimal(watts), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Power; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PowerUnit BaseUnit => PowerUnit.Watt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Power quantity. - /// - public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); - - /// - /// Get Power in BoilerHorsepower. - /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); - - /// - /// Get Power in BritishThermalUnitsPerHour. - /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); - - /// - /// Get Power in Decawatts. - /// - public double Decawatts => As(PowerUnit.Decawatt); - - /// - /// Get Power in Deciwatts. - /// - public double Deciwatts => As(PowerUnit.Deciwatt); - - /// - /// Get Power in ElectricalHorsepower. - /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); - - /// - /// Get Power in Femtowatts. - /// - public double Femtowatts => As(PowerUnit.Femtowatt); - - /// - /// Get Power in Gigawatts. - /// - public double Gigawatts => As(PowerUnit.Gigawatt); - - /// - /// Get Power in HydraulicHorsepower. - /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); - - /// - /// Get Power in KilobritishThermalUnitsPerHour. - /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); - - /// - /// Get Power in Kilowatts. - /// - public double Kilowatts => As(PowerUnit.Kilowatt); - - /// - /// Get Power in MechanicalHorsepower. - /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); - - /// - /// Get Power in Megawatts. - /// - public double Megawatts => As(PowerUnit.Megawatt); - - /// - /// Get Power in MetricHorsepower. - /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); - - /// - /// Get Power in Microwatts. - /// - public double Microwatts => As(PowerUnit.Microwatt); - - /// - /// Get Power in Milliwatts. - /// - public double Milliwatts => As(PowerUnit.Milliwatt); - - /// - /// Get Power in Nanowatts. - /// - public double Nanowatts => As(PowerUnit.Nanowatt); - - /// - /// Get Power in Petawatts. - /// - public double Petawatts => As(PowerUnit.Petawatt); - - /// - /// Get Power in Picowatts. - /// - public double Picowatts => As(PowerUnit.Picowatt); - - /// - /// Get Power in Terawatts. - /// - public double Terawatts => As(PowerUnit.Terawatt); - - /// - /// Get Power in Watts. - /// - public double Watts => As(PowerUnit.Watt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Watt. - /// - public static Power Zero => new Power(0, BaseUnit); - - /// - /// Get Power from BoilerHorsepower. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBoilerHorsepower(double boilerhorsepower) -#else - public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) -#endif - { - decimal value = (decimal) boilerhorsepower; - return new Power(value, PowerUnit.BoilerHorsepower); - } - - /// - /// Get Power from BritishThermalUnitsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) -#else - public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) -#endif - { - decimal value = (decimal) britishthermalunitsperhour; - return new Power(value, PowerUnit.BritishThermalUnitPerHour); - } - - /// - /// Get Power from Decawatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDecawatts(double decawatts) -#else - public static Power FromDecawatts(QuantityValue decawatts) -#endif - { - decimal value = (decimal) decawatts; - return new Power(value, PowerUnit.Decawatt); - } - - /// - /// Get Power from Deciwatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDeciwatts(double deciwatts) -#else - public static Power FromDeciwatts(QuantityValue deciwatts) -#endif - { - decimal value = (decimal) deciwatts; - return new Power(value, PowerUnit.Deciwatt); - } - - /// - /// Get Power from ElectricalHorsepower. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromElectricalHorsepower(double electricalhorsepower) -#else - public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) -#endif - { - decimal value = (decimal) electricalhorsepower; - return new Power(value, PowerUnit.ElectricalHorsepower); - } - - /// - /// Get Power from Femtowatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromFemtowatts(double femtowatts) -#else - public static Power FromFemtowatts(QuantityValue femtowatts) -#endif - { - decimal value = (decimal) femtowatts; - return new Power(value, PowerUnit.Femtowatt); - } - - /// - /// Get Power from Gigawatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromGigawatts(double gigawatts) -#else - public static Power FromGigawatts(QuantityValue gigawatts) -#endif - { - decimal value = (decimal) gigawatts; - return new Power(value, PowerUnit.Gigawatt); - } - - /// - /// Get Power from HydraulicHorsepower. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromHydraulicHorsepower(double hydraulichorsepower) -#else - public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) -#endif - { - decimal value = (decimal) hydraulichorsepower; - return new Power(value, PowerUnit.HydraulicHorsepower); - } - - /// - /// Get Power from KilobritishThermalUnitsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) -#else - public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) -#endif - { - decimal value = (decimal) kilobritishthermalunitsperhour; - return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); - } - - /// - /// Get Power from Kilowatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilowatts(double kilowatts) -#else - public static Power FromKilowatts(QuantityValue kilowatts) -#endif - { - decimal value = (decimal) kilowatts; - return new Power(value, PowerUnit.Kilowatt); - } - - /// - /// Get Power from MechanicalHorsepower. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMechanicalHorsepower(double mechanicalhorsepower) -#else - public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) -#endif - { - decimal value = (decimal) mechanicalhorsepower; - return new Power(value, PowerUnit.MechanicalHorsepower); - } - - /// - /// Get Power from Megawatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMegawatts(double megawatts) -#else - public static Power FromMegawatts(QuantityValue megawatts) -#endif - { - decimal value = (decimal) megawatts; - return new Power(value, PowerUnit.Megawatt); - } - - /// - /// Get Power from MetricHorsepower. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMetricHorsepower(double metrichorsepower) -#else - public static Power FromMetricHorsepower(QuantityValue metrichorsepower) -#endif - { - decimal value = (decimal) metrichorsepower; - return new Power(value, PowerUnit.MetricHorsepower); - } - - /// - /// Get Power from Microwatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMicrowatts(double microwatts) -#else - public static Power FromMicrowatts(QuantityValue microwatts) -#endif - { - decimal value = (decimal) microwatts; - return new Power(value, PowerUnit.Microwatt); - } - - /// - /// Get Power from Milliwatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMilliwatts(double milliwatts) -#else - public static Power FromMilliwatts(QuantityValue milliwatts) -#endif - { - decimal value = (decimal) milliwatts; - return new Power(value, PowerUnit.Milliwatt); - } - - /// - /// Get Power from Nanowatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromNanowatts(double nanowatts) -#else - public static Power FromNanowatts(QuantityValue nanowatts) -#endif - { - decimal value = (decimal) nanowatts; - return new Power(value, PowerUnit.Nanowatt); - } - - /// - /// Get Power from Petawatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPetawatts(double petawatts) -#else - public static Power FromPetawatts(QuantityValue petawatts) -#endif - { - decimal value = (decimal) petawatts; - return new Power(value, PowerUnit.Petawatt); - } - - /// - /// Get Power from Picowatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPicowatts(double picowatts) -#else - public static Power FromPicowatts(QuantityValue picowatts) -#endif - { - decimal value = (decimal) picowatts; - return new Power(value, PowerUnit.Picowatt); - } - - /// - /// Get Power from Terawatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromTerawatts(double terawatts) -#else - public static Power FromTerawatts(QuantityValue terawatts) -#endif - { - decimal value = (decimal) terawatts; - return new Power(value, PowerUnit.Terawatt); - } - - /// - /// Get Power from Watts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromWatts(double watts) -#else - public static Power FromWatts(QuantityValue watts) -#endif - { - decimal value = (decimal) watts; - return new Power(value, PowerUnit.Watt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Power unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Power From(double value, PowerUnit fromUnit) -#else - public static Power From(QuantityValue value, PowerUnit fromUnit) -#endif - { - return new Power((decimal)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Power)) throw new ArgumentException("Expected type Power.", nameof(obj)); - - return CompareTo((Power)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Power other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - public override bool Equals(object obj) - { - if(obj is null || !(obj is Power)) - return false; - - var objQuantity = (Power)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Power by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Power, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Power other, Power maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Power. - public override int GetHashCode() - { - return new { type = typeof(Power), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Power to another Power with the unit representation . - /// - /// A Power with the specified unit. - public Power ToUnit(PowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Power(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case PowerUnit.BoilerHorsepower: return _value*9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return _value*0.293071m; - case PowerUnit.Decawatt: return (_value) * 1e1m; - case PowerUnit.Deciwatt: return (_value) * 1e-1m; - case PowerUnit.ElectricalHorsepower: return _value*746m; - case PowerUnit.Femtowatt: return (_value) * 1e-15m; - case PowerUnit.Gigawatt: return (_value) * 1e9m; - case PowerUnit.HydraulicHorsepower: return _value*745.69988145m; - case PowerUnit.KilobritishThermalUnitPerHour: return (_value*0.293071m) * 1e3m; - case PowerUnit.Kilowatt: return (_value) * 1e3m; - case PowerUnit.MechanicalHorsepower: return _value*745.69m; - case PowerUnit.Megawatt: return (_value) * 1e6m; - case PowerUnit.MetricHorsepower: return _value*735.49875m; - case PowerUnit.Microwatt: return (_value) * 1e-6m; - case PowerUnit.Milliwatt: return (_value) * 1e-3m; - case PowerUnit.Nanowatt: return (_value) * 1e-9m; - case PowerUnit.Petawatt: return (_value) * 1e15m; - case PowerUnit.Picowatt: return (_value) * 1e-12m; - case PowerUnit.Terawatt: return (_value) * 1e12m; - case PowerUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(PowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerUnit.BoilerHorsepower: return baseUnitValue/9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue/0.293071m; - case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; - case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; - case PowerUnit.ElectricalHorsepower: return baseUnitValue/746m; - case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; - case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; - case PowerUnit.HydraulicHorsepower: return baseUnitValue/745.69988145m; - case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue/0.293071m) / 1e3m; - case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; - case PowerUnit.MechanicalHorsepower: return baseUnitValue/745.69m; - case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; - case PowerUnit.MetricHorsepower: return baseUnitValue/735.49875m; - case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; - case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; - case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; - case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; - case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; - case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; - case PowerUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Power Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Power result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Watt - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PowerUnit ToStringDefaultUnit { get; set; } = PowerUnit.Watt; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Power - /// - public static Power MaxValue => new Power(decimal.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Power - /// - public static Power MinValue => new Power(decimal.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Power.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Power.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs b/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs deleted file mode 100644 index 6e8e0e010c..0000000000 --- a/Common/GeneratedCode/Quantities/PowerDensity.Common.g.cs +++ /dev/null @@ -1,1393 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The amount of power in a volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PowerDensity : IQuantity -#else - public partial struct PowerDensity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerDensityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PowerDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit WattPerCubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public PowerDensity(double wattspercubicmeter) - { - _value = Convert.ToDouble(wattspercubicmeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - PowerDensity(double numericValue, PowerDensityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit WattPerCubicMeter. - /// - /// Value assuming base unit WattPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PowerDensity(long wattspercubicmeter) : this(Convert.ToDouble(wattspercubicmeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit WattPerCubicMeter. - /// - /// Value assuming base unit WattPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PowerDensity(decimal wattspercubicmeter) : this(Convert.ToDouble(wattspercubicmeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PowerDensity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PowerDensity quantity. - /// - public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); - - /// - /// Get PowerDensity in DecawattsPerCubicFoot. - /// - public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); - - /// - /// Get PowerDensity in DecawattsPerCubicInch. - /// - public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); - - /// - /// Get PowerDensity in DecawattsPerCubicMeter. - /// - public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); - - /// - /// Get PowerDensity in DecawattsPerLiter. - /// - public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); - - /// - /// Get PowerDensity in DeciwattsPerCubicFoot. - /// - public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); - - /// - /// Get PowerDensity in DeciwattsPerCubicInch. - /// - public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); - - /// - /// Get PowerDensity in DeciwattsPerCubicMeter. - /// - public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); - - /// - /// Get PowerDensity in DeciwattsPerLiter. - /// - public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); - - /// - /// Get PowerDensity in GigawattsPerCubicFoot. - /// - public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); - - /// - /// Get PowerDensity in GigawattsPerCubicInch. - /// - public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); - - /// - /// Get PowerDensity in GigawattsPerCubicMeter. - /// - public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); - - /// - /// Get PowerDensity in GigawattsPerLiter. - /// - public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); - - /// - /// Get PowerDensity in KilowattsPerCubicFoot. - /// - public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); - - /// - /// Get PowerDensity in KilowattsPerCubicInch. - /// - public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); - - /// - /// Get PowerDensity in KilowattsPerCubicMeter. - /// - public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); - - /// - /// Get PowerDensity in KilowattsPerLiter. - /// - public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); - - /// - /// Get PowerDensity in MegawattsPerCubicFoot. - /// - public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); - - /// - /// Get PowerDensity in MegawattsPerCubicInch. - /// - public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); - - /// - /// Get PowerDensity in MegawattsPerCubicMeter. - /// - public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); - - /// - /// Get PowerDensity in MegawattsPerLiter. - /// - public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); - - /// - /// Get PowerDensity in MicrowattsPerCubicFoot. - /// - public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); - - /// - /// Get PowerDensity in MicrowattsPerCubicInch. - /// - public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); - - /// - /// Get PowerDensity in MicrowattsPerCubicMeter. - /// - public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); - - /// - /// Get PowerDensity in MicrowattsPerLiter. - /// - public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); - - /// - /// Get PowerDensity in MilliwattsPerCubicFoot. - /// - public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); - - /// - /// Get PowerDensity in MilliwattsPerCubicInch. - /// - public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); - - /// - /// Get PowerDensity in MilliwattsPerCubicMeter. - /// - public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); - - /// - /// Get PowerDensity in MilliwattsPerLiter. - /// - public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); - - /// - /// Get PowerDensity in NanowattsPerCubicFoot. - /// - public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); - - /// - /// Get PowerDensity in NanowattsPerCubicInch. - /// - public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); - - /// - /// Get PowerDensity in NanowattsPerCubicMeter. - /// - public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); - - /// - /// Get PowerDensity in NanowattsPerLiter. - /// - public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); - - /// - /// Get PowerDensity in PicowattsPerCubicFoot. - /// - public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); - - /// - /// Get PowerDensity in PicowattsPerCubicInch. - /// - public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); - - /// - /// Get PowerDensity in PicowattsPerCubicMeter. - /// - public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); - - /// - /// Get PowerDensity in PicowattsPerLiter. - /// - public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); - - /// - /// Get PowerDensity in TerawattsPerCubicFoot. - /// - public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); - - /// - /// Get PowerDensity in TerawattsPerCubicInch. - /// - public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); - - /// - /// Get PowerDensity in TerawattsPerCubicMeter. - /// - public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); - - /// - /// Get PowerDensity in TerawattsPerLiter. - /// - public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); - - /// - /// Get PowerDensity in WattsPerCubicFoot. - /// - public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); - - /// - /// Get PowerDensity in WattsPerCubicInch. - /// - public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); - - /// - /// Get PowerDensity in WattsPerCubicMeter. - /// - public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); - - /// - /// Get PowerDensity in WattsPerLiter. - /// - public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. - /// - public static PowerDensity Zero => new PowerDensity(0, BaseUnit); - - /// - /// Get PowerDensity from DecawattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) -#else - public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) -#endif - { - double value = (double) decawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); - } - - /// - /// Get PowerDensity from DecawattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) -#else - public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) -#endif - { - double value = (double) decawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); - } - - /// - /// Get PowerDensity from DecawattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) -#else - public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) -#endif - { - double value = (double) decawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); - } - - /// - /// Get PowerDensity from DecawattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) -#else - public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) -#endif - { - double value = (double) decawattsperliter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) -#else - public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) -#endif - { - double value = (double) deciwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) -#else - public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) -#endif - { - double value = (double) deciwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); - } - - /// - /// Get PowerDensity from DeciwattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) -#else - public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) -#endif - { - double value = (double) deciwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); - } - - /// - /// Get PowerDensity from DeciwattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) -#else - public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) -#endif - { - double value = (double) deciwattsperliter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); - } - - /// - /// Get PowerDensity from GigawattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) -#else - public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) -#endif - { - double value = (double) gigawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); - } - - /// - /// Get PowerDensity from GigawattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) -#else - public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) -#endif - { - double value = (double) gigawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); - } - - /// - /// Get PowerDensity from GigawattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) -#else - public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) -#endif - { - double value = (double) gigawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); - } - - /// - /// Get PowerDensity from GigawattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) -#else - public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) -#endif - { - double value = (double) gigawattsperliter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); - } - - /// - /// Get PowerDensity from KilowattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) -#else - public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) -#endif - { - double value = (double) kilowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); - } - - /// - /// Get PowerDensity from KilowattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) -#else - public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) -#endif - { - double value = (double) kilowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); - } - - /// - /// Get PowerDensity from KilowattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) -#else - public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) -#endif - { - double value = (double) kilowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); - } - - /// - /// Get PowerDensity from KilowattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) -#else - public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) -#endif - { - double value = (double) kilowattsperliter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); - } - - /// - /// Get PowerDensity from MegawattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) -#else - public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) -#endif - { - double value = (double) megawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); - } - - /// - /// Get PowerDensity from MegawattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) -#else - public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) -#endif - { - double value = (double) megawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); - } - - /// - /// Get PowerDensity from MegawattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) -#else - public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) -#endif - { - double value = (double) megawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); - } - - /// - /// Get PowerDensity from MegawattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) -#else - public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) -#endif - { - double value = (double) megawattsperliter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) -#else - public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) -#endif - { - double value = (double) microwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) -#else - public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) -#endif - { - double value = (double) microwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); - } - - /// - /// Get PowerDensity from MicrowattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) -#else - public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) -#endif - { - double value = (double) microwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); - } - - /// - /// Get PowerDensity from MicrowattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) -#else - public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) -#endif - { - double value = (double) microwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) -#else - public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) -#endif - { - double value = (double) milliwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) -#else - public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) -#endif - { - double value = (double) milliwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); - } - - /// - /// Get PowerDensity from MilliwattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) -#else - public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) -#endif - { - double value = (double) milliwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); - } - - /// - /// Get PowerDensity from MilliwattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) -#else - public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) -#endif - { - double value = (double) milliwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); - } - - /// - /// Get PowerDensity from NanowattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) -#else - public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) -#endif - { - double value = (double) nanowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); - } - - /// - /// Get PowerDensity from NanowattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) -#else - public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) -#endif - { - double value = (double) nanowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); - } - - /// - /// Get PowerDensity from NanowattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) -#else - public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) -#endif - { - double value = (double) nanowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); - } - - /// - /// Get PowerDensity from NanowattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) -#else - public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) -#endif - { - double value = (double) nanowattsperliter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); - } - - /// - /// Get PowerDensity from PicowattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) -#else - public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) -#endif - { - double value = (double) picowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); - } - - /// - /// Get PowerDensity from PicowattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) -#else - public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) -#endif - { - double value = (double) picowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); - } - - /// - /// Get PowerDensity from PicowattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) -#else - public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) -#endif - { - double value = (double) picowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); - } - - /// - /// Get PowerDensity from PicowattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) -#else - public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) -#endif - { - double value = (double) picowattsperliter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); - } - - /// - /// Get PowerDensity from TerawattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) -#else - public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) -#endif - { - double value = (double) terawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); - } - - /// - /// Get PowerDensity from TerawattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) -#else - public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) -#endif - { - double value = (double) terawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); - } - - /// - /// Get PowerDensity from TerawattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) -#else - public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) -#endif - { - double value = (double) terawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); - } - - /// - /// Get PowerDensity from TerawattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) -#else - public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) -#endif - { - double value = (double) terawattsperliter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); - } - - /// - /// Get PowerDensity from WattsPerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) -#else - public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) -#endif - { - double value = (double) wattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); - } - - /// - /// Get PowerDensity from WattsPerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) -#else - public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) -#endif - { - double value = (double) wattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); - } - - /// - /// Get PowerDensity from WattsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) -#else - public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) -#endif - { - double value = (double) wattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); - } - - /// - /// Get PowerDensity from WattsPerLiter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerLiter(double wattsperliter) -#else - public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) -#endif - { - double value = (double) wattsperliter; - return new PowerDensity(value, PowerDensityUnit.WattPerLiter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerDensity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerDensity From(double value, PowerDensityUnit fromUnit) -#else - public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) -#endif - { - return new PowerDensity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PowerDensity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); - - return CompareTo((PowerDensity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PowerDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is PowerDensity)) - return false; - - var objQuantity = (PowerDensity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another PowerDensity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(PowerDensity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(PowerDensity other, PowerDensity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerDensity. - public override int GetHashCode() - { - return new { type = typeof(PowerDensity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerDensity to another PowerDensity with the unit representation . - /// - /// A PowerDensity with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (_value*6.102374409473228e4) * 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (_value) * 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (_value*1.0e3) * 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (_value) * 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (_value*1.0e3) * 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (_value*6.102374409473228e4) * 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (_value) * 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (_value*1.0e3) * 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (_value*6.102374409473228e4) * 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (_value) * 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (_value*1.0e3) * 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (_value*6.102374409473228e4) * 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (_value) * 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (_value*1.0e3) * 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (_value) * 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (_value*1.0e3) * 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (_value*6.102374409473228e4) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (_value) * 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (_value*1.0e3) * 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (_value) * 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (_value*1.0e3) * 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (_value*3.531466672148859e1) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (_value*6.102374409473228e4) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (_value) * 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (_value*1.0e3) * 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (_value*3.531466672148859e1) * 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (_value*6.102374409473228e4) * 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (_value) * 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (_value*1.0e3) * 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return _value*3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return _value*6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return _value; - case PowerDensityUnit.WattPerLiter: return _value*1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerDensityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (baseUnitValue) / 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (baseUnitValue/1.0e3) / 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (baseUnitValue) / 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (baseUnitValue/1.0e3) / 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (baseUnitValue) / 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (baseUnitValue/1.0e3) / 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (baseUnitValue) / 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (baseUnitValue/1.0e3) / 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (baseUnitValue) / 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (baseUnitValue/1.0e3) / 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (baseUnitValue) / 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (baseUnitValue/1.0e3) / 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (baseUnitValue) / 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (baseUnitValue/1.0e3) / 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (baseUnitValue) / 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (baseUnitValue/1.0e3) / 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (baseUnitValue) / 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (baseUnitValue/1.0e3) / 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (baseUnitValue/3.531466672148859e1) / 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (baseUnitValue/6.102374409473228e4) / 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (baseUnitValue) / 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (baseUnitValue/1.0e3) / 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return baseUnitValue/3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return baseUnitValue/6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return baseUnitValue; - case PowerDensityUnit.WattPerLiter: return baseUnitValue/1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerDensityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is WattPerCubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PowerDensityUnit ToStringDefaultUnit { get; set; } = PowerDensityUnit.WattPerCubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerDensityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PowerDensity - /// - public static PowerDensity MaxValue => new PowerDensity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PowerDensity - /// - public static PowerDensity MinValue => new PowerDensity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PowerDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerDensity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs b/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs deleted file mode 100644 index cc084e1ab1..0000000000 --- a/Common/GeneratedCode/Quantities/PowerRatio.Common.g.cs +++ /dev/null @@ -1,510 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one watt. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PowerRatio : IQuantity -#else - public partial struct PowerRatio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerRatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PowerRatio() - { - } - - /// - /// Creates the quantity with the given value in the base unit DecibelWatt. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public PowerRatio(double decibelwatts) - { - _value = Convert.ToDouble(decibelwatts); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - PowerRatio(double numericValue, PowerRatioUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit DecibelWatt. - /// - /// Value assuming base unit DecibelWatt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PowerRatio(long decibelwatts) : this(Convert.ToDouble(decibelwatts), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit DecibelWatt. - /// - /// Value assuming base unit DecibelWatt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PowerRatio(decimal decibelwatts) : this(Convert.ToDouble(decibelwatts), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PowerRatio; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PowerRatio quantity. - /// - public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); - - /// - /// Get PowerRatio in DecibelMilliwatts. - /// - public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); - - /// - /// Get PowerRatio in DecibelWatts. - /// - public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. - /// - public static PowerRatio Zero => new PowerRatio(0, BaseUnit); - - /// - /// Get PowerRatio from DecibelMilliwatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) -#else - public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) -#endif - { - double value = (double) decibelmilliwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); - } - - /// - /// Get PowerRatio from DecibelWatts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelWatts(double decibelwatts) -#else - public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) -#endif - { - double value = (double) decibelwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelWatt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerRatio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerRatio From(double value, PowerRatioUnit fromUnit) -#else - public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) -#endif - { - return new PowerRatio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PowerRatio)) throw new ArgumentException("Expected type PowerRatio.", nameof(obj)); - - return CompareTo((PowerRatio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PowerRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is PowerRatio)) - return false; - - var objQuantity = (PowerRatio)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another PowerRatio by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(PowerRatio, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(PowerRatio other, PowerRatio maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerRatio. - public override int GetHashCode() - { - return new { type = typeof(PowerRatio), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerRatio to another PowerRatio with the unit representation . - /// - /// A PowerRatio with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PowerRatioUnit.DecibelMilliwatt: return _value - 30; - case PowerRatioUnit.DecibelWatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerRatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; - case PowerRatioUnit.DecibelWatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerRatio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerRatio result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerRatioUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is DecibelWatt - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PowerRatioUnit ToStringDefaultUnit { get; set; } = PowerRatioUnit.DecibelWatt; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PowerRatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PowerRatio - /// - public static PowerRatio MaxValue => new PowerRatio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PowerRatio - /// - public static PowerRatio MinValue => new PowerRatio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PowerRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerRatio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Pressure.Common.g.cs b/Common/GeneratedCode/Quantities/Pressure.Common.g.cs deleted file mode 100644 index 6ba6f03a84..0000000000 --- a/Common/GeneratedCode/Quantities/Pressure.Common.g.cs +++ /dev/null @@ -1,1353 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Pressure : IQuantity -#else - public partial struct Pressure : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Pressure() - { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Pascal. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Pressure(double pascals) - { - _value = Convert.ToDouble(pascals); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Pressure(double numericValue, PressureUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Pascal. - /// - /// Value assuming base unit Pascal. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Pressure(long pascals) : this(Convert.ToDouble(pascals), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Pascal. - /// - /// Value assuming base unit Pascal. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Pressure(decimal pascals) : this(Convert.ToDouble(pascals), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Pressure; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PressureUnit BaseUnit => PressureUnit.Pascal; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Pressure quantity. - /// - public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); - - /// - /// Get Pressure in Atmospheres. - /// - public double Atmospheres => As(PressureUnit.Atmosphere); - - /// - /// Get Pressure in Bars. - /// - public double Bars => As(PressureUnit.Bar); - - /// - /// Get Pressure in Centibars. - /// - public double Centibars => As(PressureUnit.Centibar); - - /// - /// Get Pressure in Decapascals. - /// - public double Decapascals => As(PressureUnit.Decapascal); - - /// - /// Get Pressure in Decibars. - /// - public double Decibars => As(PressureUnit.Decibar); - - /// - /// Get Pressure in DynesPerSquareCentimeter. - /// - public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); - - /// - /// Get Pressure in FeetOfHead. - /// - public double FeetOfHead => As(PressureUnit.FootOfHead); - - /// - /// Get Pressure in Gigapascals. - /// - public double Gigapascals => As(PressureUnit.Gigapascal); - - /// - /// Get Pressure in Hectopascals. - /// - public double Hectopascals => As(PressureUnit.Hectopascal); - - /// - /// Get Pressure in InchesOfMercury. - /// - public double InchesOfMercury => As(PressureUnit.InchOfMercury); - - /// - /// Get Pressure in Kilobars. - /// - public double Kilobars => As(PressureUnit.Kilobar); - - /// - /// Get Pressure in KilogramsForcePerSquareCentimeter. - /// - public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); - - /// - /// Get Pressure in KilogramsForcePerSquareMeter. - /// - public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); - - /// - /// Get Pressure in KilogramsForcePerSquareMillimeter. - /// - public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); - - /// - /// Get Pressure in KilonewtonsPerSquareCentimeter. - /// - public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); - - /// - /// Get Pressure in KilonewtonsPerSquareMeter. - /// - public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); - - /// - /// Get Pressure in KilonewtonsPerSquareMillimeter. - /// - public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); - - /// - /// Get Pressure in Kilopascals. - /// - public double Kilopascals => As(PressureUnit.Kilopascal); - - /// - /// Get Pressure in KilopoundsForcePerSquareFoot. - /// - public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); - - /// - /// Get Pressure in KilopoundsForcePerSquareInch. - /// - public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); - - /// - /// Get Pressure in Megabars. - /// - public double Megabars => As(PressureUnit.Megabar); - - /// - /// Get Pressure in MeganewtonsPerSquareMeter. - /// - public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); - - /// - /// Get Pressure in Megapascals. - /// - public double Megapascals => As(PressureUnit.Megapascal); - - /// - /// Get Pressure in MetersOfHead. - /// - public double MetersOfHead => As(PressureUnit.MeterOfHead); - - /// - /// Get Pressure in Microbars. - /// - public double Microbars => As(PressureUnit.Microbar); - - /// - /// Get Pressure in Micropascals. - /// - public double Micropascals => As(PressureUnit.Micropascal); - - /// - /// Get Pressure in Millibars. - /// - public double Millibars => As(PressureUnit.Millibar); - - /// - /// Get Pressure in MillimetersOfMercury. - /// - public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); - - /// - /// Get Pressure in Millipascals. - /// - public double Millipascals => As(PressureUnit.Millipascal); - - /// - /// Get Pressure in NewtonsPerSquareCentimeter. - /// - public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); - - /// - /// Get Pressure in NewtonsPerSquareMeter. - /// - public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); - - /// - /// Get Pressure in NewtonsPerSquareMillimeter. - /// - public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); - - /// - /// Get Pressure in Pascals. - /// - public double Pascals => As(PressureUnit.Pascal); - - /// - /// Get Pressure in PoundsForcePerSquareFoot. - /// - public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); - - /// - /// Get Pressure in PoundsForcePerSquareInch. - /// - public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); - - /// - /// Get Pressure in PoundsPerInchSecondSquared. - /// - public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); - - /// - /// Get Pressure in Psi. - /// - [System.Obsolete("Deprecated due to github issue #215, please use PoundForcePerSquareInch instead")] - public double Psi => As(PressureUnit.Psi); - - /// - /// Get Pressure in TechnicalAtmospheres. - /// - public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); - - /// - /// Get Pressure in TonnesForcePerSquareCentimeter. - /// - public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); - - /// - /// Get Pressure in TonnesForcePerSquareMeter. - /// - public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); - - /// - /// Get Pressure in TonnesForcePerSquareMillimeter. - /// - public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); - - /// - /// Get Pressure in Torrs. - /// - public double Torrs => As(PressureUnit.Torr); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. - /// - public static Pressure Zero => new Pressure(0, BaseUnit); - - /// - /// Get Pressure from Atmospheres. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromAtmospheres(double atmospheres) -#else - public static Pressure FromAtmospheres(QuantityValue atmospheres) -#endif - { - double value = (double) atmospheres; - return new Pressure(value, PressureUnit.Atmosphere); - } - - /// - /// Get Pressure from Bars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromBars(double bars) -#else - public static Pressure FromBars(QuantityValue bars) -#endif - { - double value = (double) bars; - return new Pressure(value, PressureUnit.Bar); - } - - /// - /// Get Pressure from Centibars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromCentibars(double centibars) -#else - public static Pressure FromCentibars(QuantityValue centibars) -#endif - { - double value = (double) centibars; - return new Pressure(value, PressureUnit.Centibar); - } - - /// - /// Get Pressure from Decapascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecapascals(double decapascals) -#else - public static Pressure FromDecapascals(QuantityValue decapascals) -#endif - { - double value = (double) decapascals; - return new Pressure(value, PressureUnit.Decapascal); - } - - /// - /// Get Pressure from Decibars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecibars(double decibars) -#else - public static Pressure FromDecibars(QuantityValue decibars) -#endif - { - double value = (double) decibars; - return new Pressure(value, PressureUnit.Decibar); - } - - /// - /// Get Pressure from DynesPerSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDynesPerSquareCentimeter(double dynespersquarecentimeter) -#else - public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquarecentimeter) -#endif - { - double value = (double) dynespersquarecentimeter; - return new Pressure(value, PressureUnit.DynePerSquareCentimeter); - } - - /// - /// Get Pressure from FeetOfHead. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromFeetOfHead(double feetofhead) -#else - public static Pressure FromFeetOfHead(QuantityValue feetofhead) -#endif - { - double value = (double) feetofhead; - return new Pressure(value, PressureUnit.FootOfHead); - } - - /// - /// Get Pressure from Gigapascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromGigapascals(double gigapascals) -#else - public static Pressure FromGigapascals(QuantityValue gigapascals) -#endif - { - double value = (double) gigapascals; - return new Pressure(value, PressureUnit.Gigapascal); - } - - /// - /// Get Pressure from Hectopascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromHectopascals(double hectopascals) -#else - public static Pressure FromHectopascals(QuantityValue hectopascals) -#endif - { - double value = (double) hectopascals; - return new Pressure(value, PressureUnit.Hectopascal); - } - - /// - /// Get Pressure from InchesOfMercury. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromInchesOfMercury(double inchesofmercury) -#else - public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) -#endif - { - double value = (double) inchesofmercury; - return new Pressure(value, PressureUnit.InchOfMercury); - } - - /// - /// Get Pressure from Kilobars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilobars(double kilobars) -#else - public static Pressure FromKilobars(QuantityValue kilobars) -#endif - { - double value = (double) kilobars; - return new Pressure(value, PressureUnit.Kilobar); - } - - /// - /// Get Pressure from KilogramsForcePerSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) -#else - public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) -#endif - { - double value = (double) kilogramsforcepersquarecentimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); - } - - /// - /// Get Pressure from KilogramsForcePerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) -#else - public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) -#endif - { - double value = (double) kilogramsforcepersquaremeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); - } - - /// - /// Get Pressure from KilogramsForcePerSquareMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) -#else - public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) -#endif - { - double value = (double) kilogramsforcepersquaremillimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) -#else - public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) -#endif - { - double value = (double) kilonewtonspersquarecentimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) -#else - public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) -#endif - { - double value = (double) kilonewtonspersquaremeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); - } - - /// - /// Get Pressure from KilonewtonsPerSquareMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) -#else - public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) -#endif - { - double value = (double) kilonewtonspersquaremillimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); - } - - /// - /// Get Pressure from Kilopascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopascals(double kilopascals) -#else - public static Pressure FromKilopascals(QuantityValue kilopascals) -#endif - { - double value = (double) kilopascals; - return new Pressure(value, PressureUnit.Kilopascal); - } - - /// - /// Get Pressure from KilopoundsForcePerSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) -#else - public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) -#endif - { - double value = (double) kilopoundsforcepersquarefoot; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); - } - - /// - /// Get Pressure from KilopoundsForcePerSquareInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) -#else - public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) -#endif - { - double value = (double) kilopoundsforcepersquareinch; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); - } - - /// - /// Get Pressure from Megabars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegabars(double megabars) -#else - public static Pressure FromMegabars(QuantityValue megabars) -#endif - { - double value = (double) megabars; - return new Pressure(value, PressureUnit.Megabar); - } - - /// - /// Get Pressure from MeganewtonsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMeganewtonsPerSquareMeter(double meganewtonspersquaremeter) -#else - public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) -#endif - { - double value = (double) meganewtonspersquaremeter; - return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); - } - - /// - /// Get Pressure from Megapascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegapascals(double megapascals) -#else - public static Pressure FromMegapascals(QuantityValue megapascals) -#endif - { - double value = (double) megapascals; - return new Pressure(value, PressureUnit.Megapascal); - } - - /// - /// Get Pressure from MetersOfHead. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMetersOfHead(double metersofhead) -#else - public static Pressure FromMetersOfHead(QuantityValue metersofhead) -#endif - { - double value = (double) metersofhead; - return new Pressure(value, PressureUnit.MeterOfHead); - } - - /// - /// Get Pressure from Microbars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMicrobars(double microbars) -#else - public static Pressure FromMicrobars(QuantityValue microbars) -#endif - { - double value = (double) microbars; - return new Pressure(value, PressureUnit.Microbar); - } - - /// - /// Get Pressure from Micropascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMicropascals(double micropascals) -#else - public static Pressure FromMicropascals(QuantityValue micropascals) -#endif - { - double value = (double) micropascals; - return new Pressure(value, PressureUnit.Micropascal); - } - - /// - /// Get Pressure from Millibars. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillibars(double millibars) -#else - public static Pressure FromMillibars(QuantityValue millibars) -#endif - { - double value = (double) millibars; - return new Pressure(value, PressureUnit.Millibar); - } - - /// - /// Get Pressure from MillimetersOfMercury. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillimetersOfMercury(double millimetersofmercury) -#else - public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) -#endif - { - double value = (double) millimetersofmercury; - return new Pressure(value, PressureUnit.MillimeterOfMercury); - } - - /// - /// Get Pressure from Millipascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillipascals(double millipascals) -#else - public static Pressure FromMillipascals(QuantityValue millipascals) -#endif - { - double value = (double) millipascals; - return new Pressure(value, PressureUnit.Millipascal); - } - - /// - /// Get Pressure from NewtonsPerSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) -#else - public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) -#endif - { - double value = (double) newtonspersquarecentimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); - } - - /// - /// Get Pressure from NewtonsPerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) -#else - public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) -#endif - { - double value = (double) newtonspersquaremeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMeter); - } - - /// - /// Get Pressure from NewtonsPerSquareMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) -#else - public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) -#endif - { - double value = (double) newtonspersquaremillimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); - } - - /// - /// Get Pressure from Pascals. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPascals(double pascals) -#else - public static Pressure FromPascals(QuantityValue pascals) -#endif - { - double value = (double) pascals; - return new Pressure(value, PressureUnit.Pascal); - } - - /// - /// Get Pressure from PoundsForcePerSquareFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) -#else - public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) -#endif - { - double value = (double) poundsforcepersquarefoot; - return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); - } - - /// - /// Get Pressure from PoundsForcePerSquareInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) -#else - public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) -#endif - { - double value = (double) poundsforcepersquareinch; - return new Pressure(value, PressureUnit.PoundForcePerSquareInch); - } - - /// - /// Get Pressure from PoundsPerInchSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsPerInchSecondSquared(double poundsperinchsecondsquared) -#else - public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinchsecondsquared) -#endif - { - double value = (double) poundsperinchsecondsquared; - return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); - } - - /// - /// Get Pressure from Psi. - /// - [System.Obsolete("Deprecated due to github issue #215, please use PoundForcePerSquareInch instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPsi(double psi) -#else - public static Pressure FromPsi(QuantityValue psi) -#endif - { - double value = (double) psi; - return new Pressure(value, PressureUnit.Psi); - } - - /// - /// Get Pressure from TechnicalAtmospheres. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) -#else - public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) -#endif - { - double value = (double) technicalatmospheres; - return new Pressure(value, PressureUnit.TechnicalAtmosphere); - } - - /// - /// Get Pressure from TonnesForcePerSquareCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) -#else - public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) -#endif - { - double value = (double) tonnesforcepersquarecentimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); - } - - /// - /// Get Pressure from TonnesForcePerSquareMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) -#else - public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) -#endif - { - double value = (double) tonnesforcepersquaremeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); - } - - /// - /// Get Pressure from TonnesForcePerSquareMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) -#else - public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) -#endif - { - double value = (double) tonnesforcepersquaremillimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); - } - - /// - /// Get Pressure from Torrs. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTorrs(double torrs) -#else - public static Pressure FromTorrs(QuantityValue torrs) -#endif - { - double value = (double) torrs; - return new Pressure(value, PressureUnit.Torr); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Pressure unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Pressure From(double value, PressureUnit fromUnit) -#else - public static Pressure From(QuantityValue value, PressureUnit fromUnit) -#endif - { - return new Pressure((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Pressure)) throw new ArgumentException("Expected type Pressure.", nameof(obj)); - - return CompareTo((Pressure)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Pressure other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Pressure, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Pressure)) - return false; - - var objQuantity = (Pressure)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Pressure by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Pressure, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Pressure other, Pressure maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Pressure. - public override int GetHashCode() - { - return new { type = typeof(Pressure), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Pressure to another Pressure with the unit representation . - /// - /// A Pressure with the specified unit. - public Pressure ToUnit(PressureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Pressure(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PressureUnit.Atmosphere: return _value*1.01325*1e5; - case PressureUnit.Bar: return _value*1e5; - case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; - case PressureUnit.Decapascal: return (_value) * 1e1d; - case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return _value*1.0e-1; - case PressureUnit.FootOfHead: return _value*2989.0669; - case PressureUnit.Gigapascal: return (_value) * 1e9d; - case PressureUnit.Hectopascal: return (_value) * 1e2d; - case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; - case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; - case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; - case PressureUnit.Kilopascal: return (_value) * 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (_value*4.788025898033584e1) * 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (_value*6.894757293168361e3) * 1e3d; - case PressureUnit.Megabar: return (_value*1e5) * 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; - case PressureUnit.Megapascal: return (_value) * 1e6d; - case PressureUnit.MeterOfHead: return _value*9804.139432; - case PressureUnit.Microbar: return (_value*1e5) * 1e-6d; - case PressureUnit.Micropascal: return (_value) * 1e-6d; - case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; - case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; - case PressureUnit.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.PoundPerInchSecondSquared: return _value*1.785796732283465e1; - case PressureUnit.Psi: return _value*6.894757293168361e3; - case PressureUnit.TechnicalAtmosphere: return _value*9.80680592331*1e4; - case PressureUnit.TonneForcePerSquareCentimeter: return _value*9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return _value*9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return _value*9.80665e9; - case PressureUnit.Torr: return _value*1.3332266752*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); - case PressureUnit.Bar: return baseUnitValue/1e5; - case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; - case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; - case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; - case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; - case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; - case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; - case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; - case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; - case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue/9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; - case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue/4.788025898033584e1) / 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue/6.894757293168361e3) / 1e3d; - case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; - case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; - case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; - case PressureUnit.Microbar: return (baseUnitValue/1e5) / 1e-6d; - case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; - case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; - case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; - case PressureUnit.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.PoundPerInchSecondSquared: return baseUnitValue/1.785796732283465e1; - case PressureUnit.Psi: return baseUnitValue/6.894757293168361e3; - case PressureUnit.TechnicalAtmosphere: return baseUnitValue/(9.80680592331*1e4); - case PressureUnit.TonneForcePerSquareCentimeter: return baseUnitValue/9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return baseUnitValue/9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return baseUnitValue/9.80665e9; - case PressureUnit.Torr: return baseUnitValue/(1.3332266752*1e2); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Pressure Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Pressure result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Pascal - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PressureUnit ToStringDefaultUnit { get; set; } = PressureUnit.Pascal; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PressureUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Pressure - /// - public static Pressure MaxValue => new Pressure(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Pressure - /// - public static Pressure MinValue => new Pressure(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Pressure.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Pressure.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs deleted file mode 100644 index 31f7294fd7..0000000000 --- a/Common/GeneratedCode/Quantities/PressureChangeRate.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class PressureChangeRate : IQuantity -#else - public partial struct PressureChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static PressureChangeRate() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit PascalPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public PressureChangeRate(double pascalspersecond) - { - _value = Convert.ToDouble(pascalspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - PressureChangeRate(double numericValue, PressureChangeRateUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit PascalPerSecond. - /// - /// Value assuming base unit PascalPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PressureChangeRate(long pascalspersecond) : this(Convert.ToDouble(pascalspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit PascalPerSecond. - /// - /// Value assuming base unit PascalPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - PressureChangeRate(decimal pascalspersecond) : this(Convert.ToDouble(pascalspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.PressureChangeRate; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the PressureChangeRate quantity. - /// - public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get PressureChangeRate in AtmospheresPerSecond. - /// - public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); - - /// - /// Get PressureChangeRate in KilopascalsPerSecond. - /// - public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); - - /// - /// Get PressureChangeRate in MegapascalsPerSecond. - /// - public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); - - /// - /// Get PressureChangeRate in PascalsPerSecond. - /// - public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. - /// - public static PressureChangeRate Zero => new PressureChangeRate(0, BaseUnit); - - /// - /// Get PressureChangeRate from AtmospheresPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) -#else - public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) -#endif - { - double value = (double) atmospherespersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); - } - - /// - /// Get PressureChangeRate from KilopascalsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) -#else - public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) -#endif - { - double value = (double) kilopascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); - } - - /// - /// Get PressureChangeRate from MegapascalsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) -#else - public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) -#endif - { - double value = (double) megapascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); - } - - /// - /// Get PressureChangeRate from PascalsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) -#else - public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) -#endif - { - double value = (double) pascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PressureChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PressureChangeRate From(double value, PressureChangeRateUnit fromUnit) -#else - public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) -#endif - { - return new PressureChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is PressureChangeRate)) throw new ArgumentException("Expected type PressureChangeRate.", nameof(obj)); - - return CompareTo((PressureChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(PressureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PressureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is PressureChangeRate)) - return false; - - var objQuantity = (PressureChangeRate)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another PressureChangeRate by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(PressureChangeRate, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(PressureChangeRate other, PressureChangeRate maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PressureChangeRate. - public override int GetHashCode() - { - return new { type = typeof(PressureChangeRate), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . - /// - /// A PressureChangeRate with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PressureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; - case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; - case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; - case PressureChangeRateUnit.PascalPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); - case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; - case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; - case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PressureChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is PascalPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static PressureChangeRateUnit ToStringDefaultUnit { get; set; } = PressureChangeRateUnit.PascalPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(PressureChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of PressureChangeRate - /// - public static PressureChangeRate MaxValue => new PressureChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of PressureChangeRate - /// - public static PressureChangeRate MinValue => new PressureChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => PressureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Ratio.Common.g.cs b/Common/GeneratedCode/Quantities/Ratio.Common.g.cs deleted file mode 100644 index 968ce10102..0000000000 --- a/Common/GeneratedCode/Quantities/Ratio.Common.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Ratio : IQuantity -#else - public partial struct Ratio : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RatioUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Ratio() - { - } - - /// - /// Creates the quantity with the given value in the base unit DecimalFraction. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Ratio(double decimalfractions) - { - _value = Convert.ToDouble(decimalfractions); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Ratio(double numericValue, RatioUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit DecimalFraction. - /// - /// Value assuming base unit DecimalFraction. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Ratio(long decimalfractions) : this(Convert.ToDouble(decimalfractions), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit DecimalFraction. - /// - /// Value assuming base unit DecimalFraction. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Ratio(decimal decimalfractions) : this(Convert.ToDouble(decimalfractions), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Ratio; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Ratio quantity. - /// - public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); - - /// - /// Get Ratio in DecimalFractions. - /// - public double DecimalFractions => As(RatioUnit.DecimalFraction); - - /// - /// Get Ratio in PartsPerBillion. - /// - public double PartsPerBillion => As(RatioUnit.PartPerBillion); - - /// - /// Get Ratio in PartsPerMillion. - /// - public double PartsPerMillion => As(RatioUnit.PartPerMillion); - - /// - /// Get Ratio in PartsPerThousand. - /// - public double PartsPerThousand => As(RatioUnit.PartPerThousand); - - /// - /// Get Ratio in PartsPerTrillion. - /// - public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); - - /// - /// Get Ratio in Percent. - /// - public double Percent => As(RatioUnit.Percent); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. - /// - public static Ratio Zero => new Ratio(0, BaseUnit); - - /// - /// Get Ratio from DecimalFractions. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromDecimalFractions(double decimalfractions) -#else - public static Ratio FromDecimalFractions(QuantityValue decimalfractions) -#endif - { - double value = (double) decimalfractions; - return new Ratio(value, RatioUnit.DecimalFraction); - } - - /// - /// Get Ratio from PartsPerBillion. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerBillion(double partsperbillion) -#else - public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) -#endif - { - double value = (double) partsperbillion; - return new Ratio(value, RatioUnit.PartPerBillion); - } - - /// - /// Get Ratio from PartsPerMillion. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerMillion(double partspermillion) -#else - public static Ratio FromPartsPerMillion(QuantityValue partspermillion) -#endif - { - double value = (double) partspermillion; - return new Ratio(value, RatioUnit.PartPerMillion); - } - - /// - /// Get Ratio from PartsPerThousand. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerThousand(double partsperthousand) -#else - public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) -#endif - { - double value = (double) partsperthousand; - return new Ratio(value, RatioUnit.PartPerThousand); - } - - /// - /// Get Ratio from PartsPerTrillion. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerTrillion(double partspertrillion) -#else - public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) -#endif - { - double value = (double) partspertrillion; - return new Ratio(value, RatioUnit.PartPerTrillion); - } - - /// - /// Get Ratio from Percent. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPercent(double percent) -#else - public static Ratio FromPercent(QuantityValue percent) -#endif - { - double value = (double) percent; - return new Ratio(value, RatioUnit.Percent); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Ratio unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Ratio From(double value, RatioUnit fromUnit) -#else - public static Ratio From(QuantityValue value, RatioUnit fromUnit) -#endif - { - return new Ratio((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Ratio)) throw new ArgumentException("Expected type Ratio.", nameof(obj)); - - return CompareTo((Ratio)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Ratio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Ratio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Ratio)) - return false; - - var objQuantity = (Ratio)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Ratio by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Ratio, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Ratio other, Ratio maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Ratio. - public override int GetHashCode() - { - return new { type = typeof(Ratio), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Ratio to another Ratio with the unit representation . - /// - /// A Ratio with the specified unit. - public Ratio ToUnit(RatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Ratio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RatioUnit.DecimalFraction: return _value; - case RatioUnit.PartPerBillion: return _value/1e9; - case RatioUnit.PartPerMillion: return _value/1e6; - case RatioUnit.PartPerThousand: return _value/1e3; - case RatioUnit.PartPerTrillion: return _value/1e12; - case RatioUnit.Percent: return _value/1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RatioUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RatioUnit.DecimalFraction: return baseUnitValue; - case RatioUnit.PartPerBillion: return baseUnitValue*1e9; - case RatioUnit.PartPerMillion: return baseUnitValue*1e6; - case RatioUnit.PartPerThousand: return baseUnitValue*1e3; - case RatioUnit.PartPerTrillion: return baseUnitValue*1e12; - case RatioUnit.Percent: return baseUnitValue*1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Ratio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Ratio result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RatioUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is DecimalFraction - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static RatioUnit ToStringDefaultUnit { get; set; } = RatioUnit.DecimalFraction; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RatioUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Ratio - /// - public static Ratio MaxValue => new Ratio(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Ratio - /// - public static Ratio MinValue => new Ratio(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Ratio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Ratio.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs deleted file mode 100644 index dc65fe6a37..0000000000 --- a/Common/GeneratedCode/Quantities/ReactiveEnergy.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ReactiveEnergy : IQuantity -#else - public partial struct ReactiveEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactiveEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ReactiveEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit VoltampereReactiveHour. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ReactiveEnergy(double voltamperereactivehours) - { - _value = Convert.ToDouble(voltamperereactivehours); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ReactiveEnergy(double numericValue, ReactiveEnergyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltampereReactiveHour. - /// - /// Value assuming base unit VoltampereReactiveHour. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ReactiveEnergy(long voltamperereactivehours) : this(Convert.ToDouble(voltamperereactivehours), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltampereReactiveHour. - /// - /// Value assuming base unit VoltampereReactiveHour. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ReactiveEnergy(decimal voltamperereactivehours) : this(Convert.ToDouble(voltamperereactivehours), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ReactiveEnergy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ReactiveEnergy quantity. - /// - public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); - - /// - /// Get ReactiveEnergy in KilovoltampereReactiveHours. - /// - public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); - - /// - /// Get ReactiveEnergy in MegavoltampereReactiveHours. - /// - public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); - - /// - /// Get ReactiveEnergy in VoltampereReactiveHours. - /// - public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. - /// - public static ReactiveEnergy Zero => new ReactiveEnergy(0, BaseUnit); - - /// - /// Get ReactiveEnergy from KilovoltampereReactiveHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) -#else - public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) -#endif - { - double value = (double) kilovoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); - } - - /// - /// Get ReactiveEnergy from MegavoltampereReactiveHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) -#else - public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) -#endif - { - double value = (double) megavoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); - } - - /// - /// Get ReactiveEnergy from VoltampereReactiveHours. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) -#else - public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) -#endif - { - double value = (double) voltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactiveEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) -#else - public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) -#endif - { - return new ReactiveEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactiveEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ReactiveEnergy)) throw new ArgumentException("Expected type ReactiveEnergy.", nameof(obj)); - - return CompareTo((ReactiveEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ReactiveEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactiveEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ReactiveEnergy)) - return false; - - var objQuantity = (ReactiveEnergy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ReactiveEnergy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ReactiveEnergy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ReactiveEnergy other, ReactiveEnergy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactiveEnergy. - public override int GetHashCode() - { - return new { type = typeof(ReactiveEnergy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactiveEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . - /// - /// A ReactiveEnergy with the specified unit. - public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactiveEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactiveEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactiveEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactiveEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltampereReactiveHour - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ReactiveEnergyUnit ToStringDefaultUnit { get; set; } = ReactiveEnergyUnit.VoltampereReactiveHour; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ReactiveEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MaxValue => new ReactiveEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MinValue => new ReactiveEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ReactiveEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs b/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs deleted file mode 100644 index 95fd1c5e60..0000000000 --- a/Common/GeneratedCode/Quantities/ReactivePower.Common.g.cs +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ReactivePower : IQuantity -#else - public partial struct ReactivePower : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactivePowerUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ReactivePower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit VoltampereReactive. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ReactivePower(double voltamperesreactive) - { - _value = Convert.ToDouble(voltamperesreactive); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ReactivePower(double numericValue, ReactivePowerUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit VoltampereReactive. - /// - /// Value assuming base unit VoltampereReactive. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ReactivePower(long voltamperesreactive) : this(Convert.ToDouble(voltamperesreactive), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit VoltampereReactive. - /// - /// Value assuming base unit VoltampereReactive. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ReactivePower(decimal voltamperesreactive) : this(Convert.ToDouble(voltamperesreactive), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ReactivePower; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ReactivePower quantity. - /// - public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); - - /// - /// Get ReactivePower in GigavoltamperesReactive. - /// - public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); - - /// - /// Get ReactivePower in KilovoltamperesReactive. - /// - public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); - - /// - /// Get ReactivePower in MegavoltamperesReactive. - /// - public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); - - /// - /// Get ReactivePower in VoltamperesReactive. - /// - public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. - /// - public static ReactivePower Zero => new ReactivePower(0, BaseUnit); - - /// - /// Get ReactivePower from GigavoltamperesReactive. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) -#else - public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) -#endif - { - double value = (double) gigavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); - } - - /// - /// Get ReactivePower from KilovoltamperesReactive. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) -#else - public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) -#endif - { - double value = (double) kilovoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); - } - - /// - /// Get ReactivePower from MegavoltamperesReactive. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) -#else - public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) -#endif - { - double value = (double) megavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); - } - - /// - /// Get ReactivePower from VoltamperesReactive. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) -#else - public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) -#endif - { - double value = (double) voltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactivePower unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactivePower From(double value, ReactivePowerUnit fromUnit) -#else - public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) -#endif - { - return new ReactivePower((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactivePowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ReactivePower)) throw new ArgumentException("Expected type ReactivePower.", nameof(obj)); - - return CompareTo((ReactivePower)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ReactivePower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactivePower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ReactivePower)) - return false; - - var objQuantity = (ReactivePower)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ReactivePower by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ReactivePower, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ReactivePower other, ReactivePower maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactivePower. - public override int GetHashCode() - { - return new { type = typeof(ReactivePower), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactivePowerUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactivePower to another ReactivePower with the unit representation . - /// - /// A ReactivePower with the specified unit. - public ReactivePower ToUnit(ReactivePowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactivePower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (_value) * 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (_value) * 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (_value) * 1e6d; - case ReactivePowerUnit.VoltampereReactive: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactivePowerUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (baseUnitValue) / 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (baseUnitValue) / 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (baseUnitValue) / 1e6d; - case ReactivePowerUnit.VoltampereReactive: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactivePower Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactivePower result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactivePowerUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is VoltampereReactive - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ReactivePowerUnit ToStringDefaultUnit { get; set; } = ReactivePowerUnit.VoltampereReactive; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ReactivePowerUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ReactivePower - /// - public static ReactivePower MaxValue => new ReactivePower(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ReactivePower - /// - public static ReactivePower MinValue => new ReactivePower(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ReactivePower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactivePower.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs deleted file mode 100644 index cbc6b16d45..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalAcceleration.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Angular acceleration is the rate of change of rotational speed. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalAcceleration : IQuantity -#else - public partial struct RotationalAcceleration : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalAccelerationUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalAcceleration() - { - BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit RadianPerSecondSquared. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public RotationalAcceleration(double radianspersecondsquared) - { - _value = Convert.ToDouble(radianspersecondsquared); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalAcceleration(double numericValue, RotationalAccelerationUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit RadianPerSecondSquared. - /// - /// Value assuming base unit RadianPerSecondSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalAcceleration(long radianspersecondsquared) : this(Convert.ToDouble(radianspersecondsquared), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit RadianPerSecondSquared. - /// - /// Value assuming base unit RadianPerSecondSquared. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalAcceleration(decimal radianspersecondsquared) : this(Convert.ToDouble(radianspersecondsquared), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalAcceleration; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalAcceleration quantity. - /// - public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); - - /// - /// Get RotationalAcceleration in DegreesPerSecondSquared. - /// - public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); - - /// - /// Get RotationalAcceleration in RadiansPerSecondSquared. - /// - public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); - - /// - /// Get RotationalAcceleration in RevolutionsPerMinutePerSecond. - /// - public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. - /// - public static RotationalAcceleration Zero => new RotationalAcceleration(0, BaseUnit); - - /// - /// Get RotationalAcceleration from DegreesPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) -#else - public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) -#endif - { - double value = (double) degreespersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); - } - - /// - /// Get RotationalAcceleration from RadiansPerSecondSquared. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) -#else - public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) -#endif - { - double value = (double) radianspersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); - } - - /// - /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) -#else - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) -#endif - { - double value = (double) revolutionsperminutepersecond; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalAcceleration unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) -#else - public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) -#endif - { - return new RotationalAcceleration((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalAccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalAcceleration)) throw new ArgumentException("Expected type RotationalAcceleration.", nameof(obj)); - - return CompareTo((RotationalAcceleration)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalAcceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalAcceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is RotationalAcceleration)) - return false; - - var objQuantity = (RotationalAcceleration)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another RotationalAcceleration by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(RotationalAcceleration, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(RotationalAcceleration other, RotationalAcceleration maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalAcceleration. - public override int GetHashCode() - { - return new { type = typeof(RotationalAcceleration), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . - /// - /// A RotationalAcceleration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalAcceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; - case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalAccelerationUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; - case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalAcceleration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalAccelerationUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is RadianPerSecondSquared - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static RotationalAccelerationUnit ToStringDefaultUnit { get; set; } = RotationalAccelerationUnit.RadianPerSecondSquared; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalAccelerationUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MaxValue => new RotationalAcceleration(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MinValue => new RotationalAcceleration(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalAcceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs deleted file mode 100644 index 9613a8574a..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalSpeed.Common.g.cs +++ /dev/null @@ -1,742 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalSpeed : IQuantity -#else - public partial struct RotationalSpeed : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalSpeedUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalSpeed() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit RadianPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public RotationalSpeed(double radianspersecond) - { - _value = Convert.ToDouble(radianspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalSpeed(double numericValue, RotationalSpeedUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit RadianPerSecond. - /// - /// Value assuming base unit RadianPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalSpeed(long radianspersecond) : this(Convert.ToDouble(radianspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit RadianPerSecond. - /// - /// Value assuming base unit RadianPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalSpeed(decimal radianspersecond) : this(Convert.ToDouble(radianspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalSpeed; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalSpeed quantity. - /// - public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); - - /// - /// Get RotationalSpeed in CentiradiansPerSecond. - /// - public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); - - /// - /// Get RotationalSpeed in DeciradiansPerSecond. - /// - public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); - - /// - /// Get RotationalSpeed in DegreesPerMinute. - /// - public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); - - /// - /// Get RotationalSpeed in DegreesPerSecond. - /// - public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); - - /// - /// Get RotationalSpeed in MicrodegreesPerSecond. - /// - public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); - - /// - /// Get RotationalSpeed in MicroradiansPerSecond. - /// - public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); - - /// - /// Get RotationalSpeed in MillidegreesPerSecond. - /// - public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); - - /// - /// Get RotationalSpeed in MilliradiansPerSecond. - /// - public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); - - /// - /// Get RotationalSpeed in NanodegreesPerSecond. - /// - public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); - - /// - /// Get RotationalSpeed in NanoradiansPerSecond. - /// - public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); - - /// - /// Get RotationalSpeed in RadiansPerSecond. - /// - public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); - - /// - /// Get RotationalSpeed in RevolutionsPerMinute. - /// - public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); - - /// - /// Get RotationalSpeed in RevolutionsPerSecond. - /// - public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. - /// - public static RotationalSpeed Zero => new RotationalSpeed(0, BaseUnit); - - /// - /// Get RotationalSpeed from CentiradiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) -#else - public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) -#endif - { - double value = (double) centiradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); - } - - /// - /// Get RotationalSpeed from DeciradiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) -#else - public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) -#endif - { - double value = (double) deciradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); - } - - /// - /// Get RotationalSpeed from DegreesPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) -#else - public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) -#endif - { - double value = (double) degreesperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); - } - - /// - /// Get RotationalSpeed from DegreesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) -#else - public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) -#endif - { - double value = (double) degreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); - } - - /// - /// Get RotationalSpeed from MicrodegreesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) -#else - public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) -#endif - { - double value = (double) microdegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); - } - - /// - /// Get RotationalSpeed from MicroradiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) -#else - public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) -#endif - { - double value = (double) microradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); - } - - /// - /// Get RotationalSpeed from MillidegreesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) -#else - public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) -#endif - { - double value = (double) millidegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); - } - - /// - /// Get RotationalSpeed from MilliradiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) -#else - public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) -#endif - { - double value = (double) milliradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); - } - - /// - /// Get RotationalSpeed from NanodegreesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) -#else - public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) -#endif - { - double value = (double) nanodegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); - } - - /// - /// Get RotationalSpeed from NanoradiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) -#else - public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) -#endif - { - double value = (double) nanoradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); - } - - /// - /// Get RotationalSpeed from RadiansPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) -#else - public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) -#endif - { - double value = (double) radianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); - } - - /// - /// Get RotationalSpeed from RevolutionsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) -#else - public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) -#endif - { - double value = (double) revolutionsperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); - } - - /// - /// Get RotationalSpeed from RevolutionsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) -#else - public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) -#endif - { - double value = (double) revolutionspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalSpeed unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) -#else - public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) -#endif - { - return new RotationalSpeed((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalSpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalSpeed)) throw new ArgumentException("Expected type RotationalSpeed.", nameof(obj)); - - return CompareTo((RotationalSpeed)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalSpeed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalSpeed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is RotationalSpeed)) - return false; - - var objQuantity = (RotationalSpeed)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another RotationalSpeed by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(RotationalSpeed, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(RotationalSpeed other, RotationalSpeed maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalSpeed. - public override int GetHashCode() - { - return new { type = typeof(RotationalSpeed), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . - /// - /// A RotationalSpeed with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalSpeed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (_value) * 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (_value) * 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (Math.PI/(180*60))*_value; - case RotationalSpeedUnit.DegreePerSecond: return (Math.PI/180)*_value; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((Math.PI/180)*_value) * 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (_value) * 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((Math.PI/180)*_value) * 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (_value) * 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((Math.PI/180)*_value) * 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (_value) * 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return _value; - case RotationalSpeedUnit.RevolutionPerMinute: return (_value*6.2831853072)/60; - case RotationalSpeedUnit.RevolutionPerSecond: return _value*6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalSpeedUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (baseUnitValue) / 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (baseUnitValue) / 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (180*60/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.DegreePerSecond: return (180/Math.PI)*baseUnitValue; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return baseUnitValue; - case RotationalSpeedUnit.RevolutionPerMinute: return (baseUnitValue/6.2831853072)*60; - case RotationalSpeedUnit.RevolutionPerSecond: return baseUnitValue/6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalSpeed Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalSpeedUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is RadianPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static RotationalSpeedUnit ToStringDefaultUnit { get; set; } = RotationalSpeedUnit.RadianPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalSpeedUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalSpeed - /// - public static RotationalSpeed MaxValue => new RotationalSpeed(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalSpeed - /// - public static RotationalSpeed MinValue => new RotationalSpeed(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalSpeed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs deleted file mode 100644 index 1acea7cd26..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalStiffness.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalStiffness : IQuantity -#else - public partial struct RotationalStiffness : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalStiffness() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonMeterPerRadian. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public RotationalStiffness(double newtonmetersperradian) - { - _value = Convert.ToDouble(newtonmetersperradian); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalStiffness(double numericValue, RotationalStiffnessUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeterPerRadian. - /// - /// Value assuming base unit NewtonMeterPerRadian. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalStiffness(long newtonmetersperradian) : this(Convert.ToDouble(newtonmetersperradian), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeterPerRadian. - /// - /// Value assuming base unit NewtonMeterPerRadian. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalStiffness(decimal newtonmetersperradian) : this(Convert.ToDouble(newtonmetersperradian), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalStiffness; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalStiffness quantity. - /// - public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); - - /// - /// Get RotationalStiffness in KilonewtonMetersPerRadian. - /// - public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); - - /// - /// Get RotationalStiffness in MeganewtonMetersPerRadian. - /// - public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); - - /// - /// Get RotationalStiffness in NewtonMetersPerRadian. - /// - public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. - /// - public static RotationalStiffness Zero => new RotationalStiffness(0, BaseUnit); - - /// - /// Get RotationalStiffness from KilonewtonMetersPerRadian. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMetersPerRadian(double kilonewtonmetersperradian) -#else - public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) -#endif - { - double value = (double) kilonewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); - } - - /// - /// Get RotationalStiffness from MeganewtonMetersPerRadian. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMetersPerRadian(double meganewtonmetersperradian) -#else - public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) -#endif - { - double value = (double) meganewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); - } - - /// - /// Get RotationalStiffness from NewtonMetersPerRadian. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMetersPerRadian(double newtonmetersperradian) -#else - public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) -#endif - { - double value = (double) newtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffness unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) -#else - public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) -#endif - { - return new RotationalStiffness((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalStiffness)) throw new ArgumentException("Expected type RotationalStiffness.", nameof(obj)); - - return CompareTo((RotationalStiffness)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalStiffness other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffness, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is RotationalStiffness)) - return false; - - var objQuantity = (RotationalStiffness)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another RotationalStiffness by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(RotationalStiffness, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(RotationalStiffness other, RotationalStiffness maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffness. - public override int GetHashCode() - { - return new { type = typeof(RotationalStiffness), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . - /// - /// A RotationalStiffness with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffness(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; - case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; - case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffness Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonMeterPerRadian - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static RotationalStiffnessUnit ToStringDefaultUnit { get; set; } = RotationalStiffnessUnit.NewtonMeterPerRadian; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalStiffnessUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalStiffness - /// - public static RotationalStiffness MaxValue => new RotationalStiffness(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalStiffness - /// - public static RotationalStiffness MinValue => new RotationalStiffness(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalStiffness.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs b/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs deleted file mode 100644 index 2ddb3ee574..0000000000 --- a/Common/GeneratedCode/Quantities/RotationalStiffnessPerLength.Common.g.cs +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class RotationalStiffnessPerLength : IQuantity -#else - public partial struct RotationalStiffnessPerLength : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessPerLengthUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static RotationalStiffnessPerLength() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonMeterPerRadianPerMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public RotationalStiffnessPerLength(double newtonmetersperradianpermeter) - { - _value = Convert.ToDouble(newtonmetersperradianpermeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - RotationalStiffnessPerLength(double numericValue, RotationalStiffnessPerLengthUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeterPerRadianPerMeter. - /// - /// Value assuming base unit NewtonMeterPerRadianPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalStiffnessPerLength(long newtonmetersperradianpermeter) : this(Convert.ToDouble(newtonmetersperradianpermeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeterPerRadianPerMeter. - /// - /// Value assuming base unit NewtonMeterPerRadianPerMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - RotationalStiffnessPerLength(decimal newtonmetersperradianpermeter) : this(Convert.ToDouble(newtonmetersperradianpermeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the RotationalStiffnessPerLength quantity. - /// - public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); - - /// - /// Get RotationalStiffnessPerLength in KilonewtonMetersPerRadianPerMeter. - /// - public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - - /// - /// Get RotationalStiffnessPerLength in MeganewtonMetersPerRadianPerMeter. - /// - public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - - /// - /// Get RotationalStiffnessPerLength in NewtonMetersPerRadianPerMeter. - /// - public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. - /// - public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(0, BaseUnit); - - /// - /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double kilonewtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) -#endif - { - double value = (double) kilonewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - } - - /// - /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double meganewtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) -#endif - { - double value = (double) meganewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - } - - /// - /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double newtonmetersperradianpermeter) -#else - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) -#endif - { - double value = (double) newtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffnessPerLength unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) -#else - public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) -#endif - { - return new RotationalStiffnessPerLength((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is RotationalStiffnessPerLength)) throw new ArgumentException("Expected type RotationalStiffnessPerLength.", nameof(obj)); - - return CompareTo((RotationalStiffnessPerLength)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(RotationalStiffnessPerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffnessPerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is RotationalStiffnessPerLength)) - return false; - - var objQuantity = (RotationalStiffnessPerLength)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another RotationalStiffnessPerLength by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(RotationalStiffnessPerLength, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffnessPerLength. - public override int GetHashCode() - { - return new { type = typeof(RotationalStiffnessPerLength), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . - /// - /// A RotationalStiffnessPerLength with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffnessPerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessPerLengthUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffnessPerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonMeterPerRadianPerMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static RotationalStiffnessPerLengthUnit ToStringDefaultUnit { get; set; } = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(RotationalStiffnessPerLengthUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MaxValue => new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MinValue => new RotationalStiffnessPerLength(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => RotationalStiffnessPerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs b/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs deleted file mode 100644 index cff028e8d9..0000000000 --- a/Common/GeneratedCode/Quantities/SolidAngle.Common.g.cs +++ /dev/null @@ -1,489 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SolidAngle : IQuantity -#else - public partial struct SolidAngle : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SolidAngleUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SolidAngle() - { - } - - /// - /// Creates the quantity with the given value in the base unit Steradian. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public SolidAngle(double steradians) - { - _value = Convert.ToDouble(steradians); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - SolidAngle(double numericValue, SolidAngleUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Steradian. - /// - /// Value assuming base unit Steradian. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SolidAngle(long steradians) : this(Convert.ToDouble(steradians), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Steradian. - /// - /// Value assuming base unit Steradian. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SolidAngle(decimal steradians) : this(Convert.ToDouble(steradians), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SolidAngle; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SolidAngle quantity. - /// - public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); - - /// - /// Get SolidAngle in Steradians. - /// - public double Steradians => As(SolidAngleUnit.Steradian); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. - /// - public static SolidAngle Zero => new SolidAngle(0, BaseUnit); - - /// - /// Get SolidAngle from Steradians. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SolidAngle FromSteradians(double steradians) -#else - public static SolidAngle FromSteradians(QuantityValue steradians) -#endif - { - double value = (double) steradians; - return new SolidAngle(value, SolidAngleUnit.Steradian); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SolidAngle unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SolidAngle From(double value, SolidAngleUnit fromUnit) -#else - public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) -#endif - { - return new SolidAngle((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SolidAngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SolidAngle)) throw new ArgumentException("Expected type SolidAngle.", nameof(obj)); - - return CompareTo((SolidAngle)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SolidAngle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SolidAngle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is SolidAngle)) - return false; - - var objQuantity = (SolidAngle)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another SolidAngle by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(SolidAngle, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(SolidAngle other, SolidAngle maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SolidAngle. - public override int GetHashCode() - { - return new { type = typeof(SolidAngle), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SolidAngle to another SolidAngle with the unit representation . - /// - /// A SolidAngle with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SolidAngle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SolidAngleUnit.Steradian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SolidAngleUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SolidAngleUnit.Steradian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SolidAngle Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SolidAngle result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SolidAngleUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Steradian - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SolidAngleUnit ToStringDefaultUnit { get; set; } = SolidAngleUnit.Steradian; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SolidAngleUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SolidAngle - /// - public static SolidAngle MaxValue => new SolidAngle(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SolidAngle - /// - public static SolidAngle MinValue => new SolidAngle(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SolidAngle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SolidAngle.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs deleted file mode 100644 index 2bfd75da0c..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificEnergy.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificEnergy - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificEnergy : IQuantity -#else - public partial struct SpecificEnergy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEnergyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificEnergy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerKilogram. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public SpecificEnergy(double joulesperkilogram) - { - _value = Convert.ToDouble(joulesperkilogram); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificEnergy(double numericValue, SpecificEnergyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKilogram. - /// - /// Value assuming base unit JoulePerKilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificEnergy(long joulesperkilogram) : this(Convert.ToDouble(joulesperkilogram), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKilogram. - /// - /// Value assuming base unit JoulePerKilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificEnergy(decimal joulesperkilogram) : this(Convert.ToDouble(joulesperkilogram), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificEnergy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificEnergy quantity. - /// - public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); - - /// - /// Get SpecificEnergy in CaloriesPerGram. - /// - public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); - - /// - /// Get SpecificEnergy in JoulesPerKilogram. - /// - public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); - - /// - /// Get SpecificEnergy in KilocaloriesPerGram. - /// - public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); - - /// - /// Get SpecificEnergy in KilojoulesPerKilogram. - /// - public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); - - /// - /// Get SpecificEnergy in KilowattHoursPerKilogram. - /// - public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); - - /// - /// Get SpecificEnergy in MegajoulesPerKilogram. - /// - public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); - - /// - /// Get SpecificEnergy in MegawattHoursPerKilogram. - /// - public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); - - /// - /// Get SpecificEnergy in WattHoursPerKilogram. - /// - public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. - /// - public static SpecificEnergy Zero => new SpecificEnergy(0, BaseUnit); - - /// - /// Get SpecificEnergy from CaloriesPerGram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) -#else - public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) -#endif - { - double value = (double) caloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); - } - - /// - /// Get SpecificEnergy from JoulesPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) -#else - public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) -#endif - { - double value = (double) joulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); - } - - /// - /// Get SpecificEnergy from KilocaloriesPerGram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) -#else - public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) -#endif - { - double value = (double) kilocaloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); - } - - /// - /// Get SpecificEnergy from KilojoulesPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) -#else - public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) -#endif - { - double value = (double) kilojoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); - } - - /// - /// Get SpecificEnergy from KilowattHoursPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) -#else - public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) -#endif - { - double value = (double) kilowatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); - } - - /// - /// Get SpecificEnergy from MegajoulesPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) -#else - public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) -#endif - { - double value = (double) megajoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); - } - - /// - /// Get SpecificEnergy from MegawattHoursPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) -#else - public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) -#endif - { - double value = (double) megawatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); - } - - /// - /// Get SpecificEnergy from WattHoursPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) -#else - public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) -#endif - { - double value = (double) watthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEnergy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) -#else - public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) -#endif - { - return new SpecificEnergy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificEnergy)) throw new ArgumentException("Expected type SpecificEnergy.", nameof(obj)); - - return CompareTo((SpecificEnergy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is SpecificEnergy)) - return false; - - var objQuantity = (SpecificEnergy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another SpecificEnergy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(SpecificEnergy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(SpecificEnergy other, SpecificEnergy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEnergy. - public override int GetHashCode() - { - return new { type = typeof(SpecificEnergy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . - /// - /// A SpecificEnergy with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; - case SpecificEnergyUnit.JoulePerKilogram: return _value; - case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; - case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEnergyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; - case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; - case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; - case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerKilogram - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SpecificEnergyUnit ToStringDefaultUnit { get; set; } = SpecificEnergyUnit.JoulePerKilogram; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificEnergyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificEnergy - /// - public static SpecificEnergy MaxValue => new SpecificEnergy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificEnergy - /// - public static SpecificEnergy MinValue => new SpecificEnergy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs deleted file mode 100644 index 41e4e8afaa..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificEntropy.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificEntropy : IQuantity -#else - public partial struct SpecificEntropy : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEntropyUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificEntropy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit JoulePerKilogramKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public SpecificEntropy(double joulesperkilogramkelvin) - { - _value = Convert.ToDouble(joulesperkilogramkelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificEntropy(double numericValue, SpecificEntropyUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKilogramKelvin. - /// - /// Value assuming base unit JoulePerKilogramKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificEntropy(long joulesperkilogramkelvin) : this(Convert.ToDouble(joulesperkilogramkelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit JoulePerKilogramKelvin. - /// - /// Value assuming base unit JoulePerKilogramKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificEntropy(decimal joulesperkilogramkelvin) : this(Convert.ToDouble(joulesperkilogramkelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificEntropy; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificEntropy quantity. - /// - public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); - - /// - /// Get SpecificEntropy in CaloriesPerGramKelvin. - /// - public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); - - /// - /// Get SpecificEntropy in JoulesPerKilogramDegreeCelsius. - /// - public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in JoulesPerKilogramKelvin. - /// - public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); - - /// - /// Get SpecificEntropy in KilocaloriesPerGramKelvin. - /// - public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); - - /// - /// Get SpecificEntropy in KilojoulesPerKilogramDegreeCelsius. - /// - public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in KilojoulesPerKilogramKelvin. - /// - public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); - - /// - /// Get SpecificEntropy in MegajoulesPerKilogramDegreeCelsius. - /// - public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - - /// - /// Get SpecificEntropy in MegajoulesPerKilogramKelvin. - /// - public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. - /// - public static SpecificEntropy Zero => new SpecificEntropy(0, BaseUnit); - - /// - /// Get SpecificEntropy from CaloriesPerGramKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) -#else - public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) -#endif - { - double value = (double) caloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); - } - - /// - /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) -#endif - { - double value = (double) joulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from JoulesPerKilogramKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) -#else - public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) -#endif - { - double value = (double) joulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); - } - - /// - /// Get SpecificEntropy from KilocaloriesPerGramKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) -#else - public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) -#endif - { - double value = (double) kilocaloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); - } - - /// - /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) -#endif - { - double value = (double) kilojoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) -#else - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) -#endif - { - double value = (double) kilojoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); - } - - /// - /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) -#else - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) -#endif - { - double value = (double) megajoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - } - - /// - /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) -#else - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) -#endif - { - double value = (double) megajoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEntropy unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) -#else - public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) -#endif - { - return new SpecificEntropy((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificEntropy)) throw new ArgumentException("Expected type SpecificEntropy.", nameof(obj)); - - return CompareTo((SpecificEntropy)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is SpecificEntropy)) - return false; - - var objQuantity = (SpecificEntropy)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another SpecificEntropy by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(SpecificEntropy, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(SpecificEntropy other, SpecificEntropy maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEntropy. - public override int GetHashCode() - { - return new { type = typeof(SpecificEntropy), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . - /// - /// A SpecificEntropy with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: return _value*4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value*4.184e3) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEntropyUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue/4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue/4.184e3) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEntropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEntropyUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is JoulePerKilogramKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SpecificEntropyUnit ToStringDefaultUnit { get; set; } = SpecificEntropyUnit.JoulePerKilogramKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificEntropyUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificEntropy - /// - public static SpecificEntropy MaxValue => new SpecificEntropy(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificEntropy - /// - public static SpecificEntropy MinValue => new SpecificEntropy(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs deleted file mode 100644 index a7563f4c9e..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificVolume.Common.g.cs +++ /dev/null @@ -1,511 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificVolume : IQuantity -#else - public partial struct SpecificVolume : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificVolumeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificVolume() - { - BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit CubicMeterPerKilogram. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public SpecificVolume(double cubicmetersperkilogram) - { - _value = Convert.ToDouble(cubicmetersperkilogram); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificVolume(double numericValue, SpecificVolumeUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerKilogram. - /// - /// Value assuming base unit CubicMeterPerKilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificVolume(long cubicmetersperkilogram) : this(Convert.ToDouble(cubicmetersperkilogram), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerKilogram. - /// - /// Value assuming base unit CubicMeterPerKilogram. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificVolume(decimal cubicmetersperkilogram) : this(Convert.ToDouble(cubicmetersperkilogram), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificVolume; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificVolume quantity. - /// - public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); - - /// - /// Get SpecificVolume in CubicFeetPerPound. - /// - public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); - - /// - /// Get SpecificVolume in CubicMetersPerKilogram. - /// - public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. - /// - public static SpecificVolume Zero => new SpecificVolume(0, BaseUnit); - - /// - /// Get SpecificVolume from CubicFeetPerPound. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicFeetPerPound(double cubicfeetperpound) -#else - public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) -#endif - { - double value = (double) cubicfeetperpound; - return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); - } - - /// - /// Get SpecificVolume from CubicMetersPerKilogram. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) -#else - public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) -#endif - { - double value = (double) cubicmetersperkilogram; - return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificVolume unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) -#else - public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) -#endif - { - return new SpecificVolume((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificVolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificVolume)) throw new ArgumentException("Expected type SpecificVolume.", nameof(obj)); - - return CompareTo((SpecificVolume)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificVolume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificVolume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is SpecificVolume)) - return false; - - var objQuantity = (SpecificVolume)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another SpecificVolume by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(SpecificVolume, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(SpecificVolume other, SpecificVolume maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificVolume. - public override int GetHashCode() - { - return new { type = typeof(SpecificVolume), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificVolume to another SpecificVolume with the unit representation . - /// - /// A SpecificVolume with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificVolume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return _value/16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificVolumeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue*16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificVolume Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificVolume result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificVolumeUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is CubicMeterPerKilogram - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SpecificVolumeUnit ToStringDefaultUnit { get; set; } = SpecificVolumeUnit.CubicMeterPerKilogram; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificVolumeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificVolume - /// - public static SpecificVolume MaxValue => new SpecificVolume(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificVolume - /// - public static SpecificVolume MinValue => new SpecificVolume(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificVolume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs b/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs deleted file mode 100644 index 6333256431..0000000000 --- a/Common/GeneratedCode/Quantities/SpecificWeight.Common.g.cs +++ /dev/null @@ -1,826 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class SpecificWeight : IQuantity -#else - public partial struct SpecificWeight : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificWeightUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static SpecificWeight() - { - BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonPerCubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public SpecificWeight(double newtonspercubicmeter) - { - _value = Convert.ToDouble(newtonspercubicmeter); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - SpecificWeight(double numericValue, SpecificWeightUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerCubicMeter. - /// - /// Value assuming base unit NewtonPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificWeight(long newtonspercubicmeter) : this(Convert.ToDouble(newtonspercubicmeter), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonPerCubicMeter. - /// - /// Value assuming base unit NewtonPerCubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - SpecificWeight(decimal newtonspercubicmeter) : this(Convert.ToDouble(newtonspercubicmeter), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.SpecificWeight; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the SpecificWeight quantity. - /// - public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicCentimeter. - /// - public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicMeter. - /// - public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); - - /// - /// Get SpecificWeight in KilogramsForcePerCubicMillimeter. - /// - public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicCentimeter. - /// - public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicMeter. - /// - public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); - - /// - /// Get SpecificWeight in KilonewtonsPerCubicMillimeter. - /// - public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); - - /// - /// Get SpecificWeight in KilopoundsForcePerCubicFoot. - /// - public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); - - /// - /// Get SpecificWeight in KilopoundsForcePerCubicInch. - /// - public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); - - /// - /// Get SpecificWeight in MeganewtonsPerCubicMeter. - /// - public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicCentimeter. - /// - public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicMeter. - /// - public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); - - /// - /// Get SpecificWeight in NewtonsPerCubicMillimeter. - /// - public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); - - /// - /// Get SpecificWeight in PoundsForcePerCubicFoot. - /// - public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); - - /// - /// Get SpecificWeight in PoundsForcePerCubicInch. - /// - public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); - - /// - /// Get SpecificWeight in TonnesForcePerCubicCentimeter. - /// - public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); - - /// - /// Get SpecificWeight in TonnesForcePerCubicMeter. - /// - public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); - - /// - /// Get SpecificWeight in TonnesForcePerCubicMillimeter. - /// - public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. - /// - public static SpecificWeight Zero => new SpecificWeight(0, BaseUnit); - - /// - /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) -#endif - { - double value = (double) kilogramsforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); - } - - /// - /// Get SpecificWeight from KilogramsForcePerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) -#endif - { - double value = (double) kilogramsforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); - } - - /// - /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) -#else - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) -#endif - { - double value = (double) kilogramsforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) -#endif - { - double value = (double) kilonewtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) -#endif - { - double value = (double) kilonewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) -#else - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) -#endif - { - double value = (double) kilonewtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); - } - - /// - /// Get SpecificWeight from KilopoundsForcePerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) -#else - public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) -#endif - { - double value = (double) kilopoundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); - } - - /// - /// Get SpecificWeight from KilopoundsForcePerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) -#else - public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) -#endif - { - double value = (double) kilopoundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); - } - - /// - /// Get SpecificWeight from MeganewtonsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromMeganewtonsPerCubicMeter(double meganewtonspercubicmeter) -#else - public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) -#endif - { - double value = (double) meganewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) -#else - public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) -#endif - { - double value = (double) newtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) -#else - public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) -#endif - { - double value = (double) newtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); - } - - /// - /// Get SpecificWeight from NewtonsPerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) -#else - public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) -#endif - { - double value = (double) newtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); - } - - /// - /// Get SpecificWeight from PoundsForcePerCubicFoot. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) -#else - public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) -#endif - { - double value = (double) poundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); - } - - /// - /// Get SpecificWeight from PoundsForcePerCubicInch. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) -#else - public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) -#endif - { - double value = (double) poundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicCentimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) -#else - public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) -#endif - { - double value = (double) tonnesforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicMeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) -#else - public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) -#endif - { - double value = (double) tonnesforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); - } - - /// - /// Get SpecificWeight from TonnesForcePerCubicMillimeter. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) -#else - public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) -#endif - { - double value = (double) tonnesforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificWeight unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) -#else - public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) -#endif - { - return new SpecificWeight((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificWeightUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is SpecificWeight)) throw new ArgumentException("Expected type SpecificWeight.", nameof(obj)); - - return CompareTo((SpecificWeight)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(SpecificWeight other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificWeight, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is SpecificWeight)) - return false; - - var objQuantity = (SpecificWeight)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another SpecificWeight by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(SpecificWeight, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(SpecificWeight other, SpecificWeight maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificWeight. - public override int GetHashCode() - { - return new { type = typeof(SpecificWeight), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificWeight to another SpecificWeight with the unit representation . - /// - /// A SpecificWeight with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificWeight(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return _value*9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return _value*9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return _value*9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (_value*1000000) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (_value) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (_value*1000000000) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (_value*1.570874638462462e2) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (_value*2.714471375263134e5) * 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (_value) * 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return _value*1000000; - case SpecificWeightUnit.NewtonPerCubicMeter: return _value; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return _value*1000000000; - case SpecificWeightUnit.PoundForcePerCubicFoot: return _value*1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return _value*2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return _value*9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return _value*9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return _value*9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificWeightUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return baseUnitValue/9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return baseUnitValue/9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (baseUnitValue*0.000001) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (baseUnitValue) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (baseUnitValue*0.000000001) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (baseUnitValue/1.570874638462462e2) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (baseUnitValue/2.714471375263134e5) / 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (baseUnitValue) / 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return baseUnitValue*0.000001; - case SpecificWeightUnit.NewtonPerCubicMeter: return baseUnitValue; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return baseUnitValue*0.000000001; - case SpecificWeightUnit.PoundForcePerCubicFoot: return baseUnitValue/1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return baseUnitValue/2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return baseUnitValue/9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return baseUnitValue/9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return baseUnitValue/9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificWeight Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificWeight result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificWeightUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonPerCubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SpecificWeightUnit ToStringDefaultUnit { get; set; } = SpecificWeightUnit.NewtonPerCubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpecificWeightUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of SpecificWeight - /// - public static SpecificWeight MaxValue => new SpecificWeight(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of SpecificWeight - /// - public static SpecificWeight MinValue => new SpecificWeight(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => SpecificWeight.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Speed.Common.g.cs b/Common/GeneratedCode/Quantities/Speed.Common.g.cs deleted file mode 100644 index 2b82cec471..0000000000 --- a/Common/GeneratedCode/Quantities/Speed.Common.g.cs +++ /dev/null @@ -1,1141 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Speed : IQuantity -#else - public partial struct Speed : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpeedUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Speed() - { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit MeterPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Speed(double meterspersecond) - { - _value = Convert.ToDouble(meterspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Speed(double numericValue, SpeedUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit MeterPerSecond. - /// - /// Value assuming base unit MeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Speed(long meterspersecond) : this(Convert.ToDouble(meterspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit MeterPerSecond. - /// - /// Value assuming base unit MeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Speed(decimal meterspersecond) : this(Convert.ToDouble(meterspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Speed; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Speed quantity. - /// - public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); - - /// - /// Get Speed in CentimetersPerHour. - /// - public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); - - /// - /// Get Speed in CentimetersPerMinutes. - /// - public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); - - /// - /// Get Speed in CentimetersPerSecond. - /// - public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); - - /// - /// Get Speed in DecimetersPerMinutes. - /// - public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); - - /// - /// Get Speed in DecimetersPerSecond. - /// - public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); - - /// - /// Get Speed in FeetPerHour. - /// - public double FeetPerHour => As(SpeedUnit.FootPerHour); - - /// - /// Get Speed in FeetPerMinute. - /// - public double FeetPerMinute => As(SpeedUnit.FootPerMinute); - - /// - /// Get Speed in FeetPerSecond. - /// - public double FeetPerSecond => As(SpeedUnit.FootPerSecond); - - /// - /// Get Speed in InchesPerHour. - /// - public double InchesPerHour => As(SpeedUnit.InchPerHour); - - /// - /// Get Speed in InchesPerMinute. - /// - public double InchesPerMinute => As(SpeedUnit.InchPerMinute); - - /// - /// Get Speed in InchesPerSecond. - /// - public double InchesPerSecond => As(SpeedUnit.InchPerSecond); - - /// - /// Get Speed in KilometersPerHour. - /// - public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); - - /// - /// Get Speed in KilometersPerMinutes. - /// - public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); - - /// - /// Get Speed in KilometersPerSecond. - /// - public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); - - /// - /// Get Speed in Knots. - /// - public double Knots => As(SpeedUnit.Knot); - - /// - /// Get Speed in MetersPerHour. - /// - public double MetersPerHour => As(SpeedUnit.MeterPerHour); - - /// - /// Get Speed in MetersPerMinutes. - /// - public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); - - /// - /// Get Speed in MetersPerSecond. - /// - public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); - - /// - /// Get Speed in MicrometersPerMinutes. - /// - public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); - - /// - /// Get Speed in MicrometersPerSecond. - /// - public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); - - /// - /// Get Speed in MilesPerHour. - /// - public double MilesPerHour => As(SpeedUnit.MilePerHour); - - /// - /// Get Speed in MillimetersPerHour. - /// - public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); - - /// - /// Get Speed in MillimetersPerMinutes. - /// - public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); - - /// - /// Get Speed in MillimetersPerSecond. - /// - public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); - - /// - /// Get Speed in NanometersPerMinutes. - /// - public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); - - /// - /// Get Speed in NanometersPerSecond. - /// - public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); - - /// - /// Get Speed in UsSurveyFeetPerHour. - /// - public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); - - /// - /// Get Speed in UsSurveyFeetPerMinute. - /// - public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); - - /// - /// Get Speed in UsSurveyFeetPerSecond. - /// - public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); - - /// - /// Get Speed in YardsPerHour. - /// - public double YardsPerHour => As(SpeedUnit.YardPerHour); - - /// - /// Get Speed in YardsPerMinute. - /// - public double YardsPerMinute => As(SpeedUnit.YardPerMinute); - - /// - /// Get Speed in YardsPerSecond. - /// - public double YardsPerSecond => As(SpeedUnit.YardPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. - /// - public static Speed Zero => new Speed(0, BaseUnit); - - /// - /// Get Speed from CentimetersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerHour(double centimetersperhour) -#else - public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) -#endif - { - double value = (double) centimetersperhour; - return new Speed(value, SpeedUnit.CentimeterPerHour); - } - - /// - /// Get Speed from CentimetersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerMinutes(double centimetersperminutes) -#else - public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) -#endif - { - double value = (double) centimetersperminutes; - return new Speed(value, SpeedUnit.CentimeterPerMinute); - } - - /// - /// Get Speed from CentimetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerSecond(double centimeterspersecond) -#else - public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) -#endif - { - double value = (double) centimeterspersecond; - return new Speed(value, SpeedUnit.CentimeterPerSecond); - } - - /// - /// Get Speed from DecimetersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerMinutes(double decimetersperminutes) -#else - public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) -#endif - { - double value = (double) decimetersperminutes; - return new Speed(value, SpeedUnit.DecimeterPerMinute); - } - - /// - /// Get Speed from DecimetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerSecond(double decimeterspersecond) -#else - public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) -#endif - { - double value = (double) decimeterspersecond; - return new Speed(value, SpeedUnit.DecimeterPerSecond); - } - - /// - /// Get Speed from FeetPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerHour(double feetperhour) -#else - public static Speed FromFeetPerHour(QuantityValue feetperhour) -#endif - { - double value = (double) feetperhour; - return new Speed(value, SpeedUnit.FootPerHour); - } - - /// - /// Get Speed from FeetPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerMinute(double feetperminute) -#else - public static Speed FromFeetPerMinute(QuantityValue feetperminute) -#endif - { - double value = (double) feetperminute; - return new Speed(value, SpeedUnit.FootPerMinute); - } - - /// - /// Get Speed from FeetPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerSecond(double feetpersecond) -#else - public static Speed FromFeetPerSecond(QuantityValue feetpersecond) -#endif - { - double value = (double) feetpersecond; - return new Speed(value, SpeedUnit.FootPerSecond); - } - - /// - /// Get Speed from InchesPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerHour(double inchesperhour) -#else - public static Speed FromInchesPerHour(QuantityValue inchesperhour) -#endif - { - double value = (double) inchesperhour; - return new Speed(value, SpeedUnit.InchPerHour); - } - - /// - /// Get Speed from InchesPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerMinute(double inchesperminute) -#else - public static Speed FromInchesPerMinute(QuantityValue inchesperminute) -#endif - { - double value = (double) inchesperminute; - return new Speed(value, SpeedUnit.InchPerMinute); - } - - /// - /// Get Speed from InchesPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerSecond(double inchespersecond) -#else - public static Speed FromInchesPerSecond(QuantityValue inchespersecond) -#endif - { - double value = (double) inchespersecond; - return new Speed(value, SpeedUnit.InchPerSecond); - } - - /// - /// Get Speed from KilometersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerHour(double kilometersperhour) -#else - public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) -#endif - { - double value = (double) kilometersperhour; - return new Speed(value, SpeedUnit.KilometerPerHour); - } - - /// - /// Get Speed from KilometersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerMinutes(double kilometersperminutes) -#else - public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) -#endif - { - double value = (double) kilometersperminutes; - return new Speed(value, SpeedUnit.KilometerPerMinute); - } - - /// - /// Get Speed from KilometersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerSecond(double kilometerspersecond) -#else - public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) -#endif - { - double value = (double) kilometerspersecond; - return new Speed(value, SpeedUnit.KilometerPerSecond); - } - - /// - /// Get Speed from Knots. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKnots(double knots) -#else - public static Speed FromKnots(QuantityValue knots) -#endif - { - double value = (double) knots; - return new Speed(value, SpeedUnit.Knot); - } - - /// - /// Get Speed from MetersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerHour(double metersperhour) -#else - public static Speed FromMetersPerHour(QuantityValue metersperhour) -#endif - { - double value = (double) metersperhour; - return new Speed(value, SpeedUnit.MeterPerHour); - } - - /// - /// Get Speed from MetersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerMinutes(double metersperminutes) -#else - public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) -#endif - { - double value = (double) metersperminutes; - return new Speed(value, SpeedUnit.MeterPerMinute); - } - - /// - /// Get Speed from MetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerSecond(double meterspersecond) -#else - public static Speed FromMetersPerSecond(QuantityValue meterspersecond) -#endif - { - double value = (double) meterspersecond; - return new Speed(value, SpeedUnit.MeterPerSecond); - } - - /// - /// Get Speed from MicrometersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerMinutes(double micrometersperminutes) -#else - public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) -#endif - { - double value = (double) micrometersperminutes; - return new Speed(value, SpeedUnit.MicrometerPerMinute); - } - - /// - /// Get Speed from MicrometersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerSecond(double micrometerspersecond) -#else - public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) -#endif - { - double value = (double) micrometerspersecond; - return new Speed(value, SpeedUnit.MicrometerPerSecond); - } - - /// - /// Get Speed from MilesPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMilesPerHour(double milesperhour) -#else - public static Speed FromMilesPerHour(QuantityValue milesperhour) -#endif - { - double value = (double) milesperhour; - return new Speed(value, SpeedUnit.MilePerHour); - } - - /// - /// Get Speed from MillimetersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerHour(double millimetersperhour) -#else - public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) -#endif - { - double value = (double) millimetersperhour; - return new Speed(value, SpeedUnit.MillimeterPerHour); - } - - /// - /// Get Speed from MillimetersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerMinutes(double millimetersperminutes) -#else - public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) -#endif - { - double value = (double) millimetersperminutes; - return new Speed(value, SpeedUnit.MillimeterPerMinute); - } - - /// - /// Get Speed from MillimetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerSecond(double millimeterspersecond) -#else - public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) -#endif - { - double value = (double) millimeterspersecond; - return new Speed(value, SpeedUnit.MillimeterPerSecond); - } - - /// - /// Get Speed from NanometersPerMinutes. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerMinutes(double nanometersperminutes) -#else - public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) -#endif - { - double value = (double) nanometersperminutes; - return new Speed(value, SpeedUnit.NanometerPerMinute); - } - - /// - /// Get Speed from NanometersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerSecond(double nanometerspersecond) -#else - public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) -#endif - { - double value = (double) nanometerspersecond; - return new Speed(value, SpeedUnit.NanometerPerSecond); - } - - /// - /// Get Speed from UsSurveyFeetPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) -#else - public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) -#endif - { - double value = (double) ussurveyfeetperhour; - return new Speed(value, SpeedUnit.UsSurveyFootPerHour); - } - - /// - /// Get Speed from UsSurveyFeetPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) -#else - public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) -#endif - { - double value = (double) ussurveyfeetperminute; - return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); - } - - /// - /// Get Speed from UsSurveyFeetPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) -#else - public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) -#endif - { - double value = (double) ussurveyfeetpersecond; - return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); - } - - /// - /// Get Speed from YardsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerHour(double yardsperhour) -#else - public static Speed FromYardsPerHour(QuantityValue yardsperhour) -#endif - { - double value = (double) yardsperhour; - return new Speed(value, SpeedUnit.YardPerHour); - } - - /// - /// Get Speed from YardsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerMinute(double yardsperminute) -#else - public static Speed FromYardsPerMinute(QuantityValue yardsperminute) -#endif - { - double value = (double) yardsperminute; - return new Speed(value, SpeedUnit.YardPerMinute); - } - - /// - /// Get Speed from YardsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerSecond(double yardspersecond) -#else - public static Speed FromYardsPerSecond(QuantityValue yardspersecond) -#endif - { - double value = (double) yardspersecond; - return new Speed(value, SpeedUnit.YardPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Speed unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Speed From(double value, SpeedUnit fromUnit) -#else - public static Speed From(QuantityValue value, SpeedUnit fromUnit) -#endif - { - return new Speed((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Speed)) throw new ArgumentException("Expected type Speed.", nameof(obj)); - - return CompareTo((Speed)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Speed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Speed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Speed)) - return false; - - var objQuantity = (Speed)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Speed by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Speed, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Speed other, Speed maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Speed. - public override int GetHashCode() - { - return new { type = typeof(Speed), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpeedUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Speed to another Speed with the unit representation . - /// - /// A Speed with the specified unit. - public Speed ToUnit(SpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Speed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; - case SpeedUnit.FootPerHour: return _value*0.3048/3600; - case SpeedUnit.FootPerMinute: return _value*0.3048/60; - case SpeedUnit.FootPerSecond: return _value*0.3048; - case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; - case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; - case SpeedUnit.InchPerSecond: return _value*2.54e-2; - case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; - case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; - case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; - case SpeedUnit.Knot: return _value*0.514444; - case SpeedUnit.MeterPerHour: return _value/3600; - case SpeedUnit.MeterPerMinute: return _value/60; - case SpeedUnit.MeterPerSecond: return _value; - case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; - case SpeedUnit.MilePerHour: return _value*0.44704; - case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; - case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; - case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; - case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; - case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; - case SpeedUnit.YardPerHour: return _value*0.9144/3600; - case SpeedUnit.YardPerMinute: return _value*0.9144/60; - case SpeedUnit.YardPerSecond: return _value*0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpeedUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; - case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; - case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; - case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; - case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; - case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; - case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; - case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; - case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; - case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; - case SpeedUnit.Knot: return baseUnitValue/0.514444; - case SpeedUnit.MeterPerHour: return baseUnitValue*3600; - case SpeedUnit.MeterPerMinute: return baseUnitValue*60; - case SpeedUnit.MeterPerSecond: return baseUnitValue; - case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; - case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; - case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; - case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; - case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; - case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; - case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; - case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; - case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; - case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Speed Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Speed result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpeedUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is MeterPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static SpeedUnit ToStringDefaultUnit { get; set; } = SpeedUnit.MeterPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(SpeedUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Speed - /// - public static Speed MaxValue => new Speed(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Speed - /// - public static Speed MinValue => new Speed(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Speed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Speed.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Temperature.Common.g.cs b/Common/GeneratedCode/Quantities/Temperature.Common.g.cs deleted file mode 100644 index 15133db34e..0000000000 --- a/Common/GeneratedCode/Quantities/Temperature.Common.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Temperature : IQuantity -#else - public partial struct Temperature : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Temperature() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit Kelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Temperature(double kelvins) - { - _value = Convert.ToDouble(kelvins); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Temperature(double numericValue, TemperatureUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Kelvin. - /// - /// Value assuming base unit Kelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Temperature(long kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Kelvin. - /// - /// Value assuming base unit Kelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Temperature(decimal kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Temperature; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Temperature quantity. - /// - public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); - - /// - /// Get Temperature in DegreesCelsius. - /// - public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); - - /// - /// Get Temperature in DegreesDelisle. - /// - public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); - - /// - /// Get Temperature in DegreesFahrenheit. - /// - public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); - - /// - /// Get Temperature in DegreesNewton. - /// - public double DegreesNewton => As(TemperatureUnit.DegreeNewton); - - /// - /// Get Temperature in DegreesRankine. - /// - public double DegreesRankine => As(TemperatureUnit.DegreeRankine); - - /// - /// Get Temperature in DegreesReaumur. - /// - public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); - - /// - /// Get Temperature in DegreesRoemer. - /// - public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); - - /// - /// Get Temperature in Kelvins. - /// - public double Kelvins => As(TemperatureUnit.Kelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static Temperature Zero => new Temperature(0, BaseUnit); - - /// - /// Get Temperature from DegreesCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesCelsius(double degreescelsius) -#else - public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) -#endif - { - double value = (double) degreescelsius; - return new Temperature(value, TemperatureUnit.DegreeCelsius); - } - - /// - /// Get Temperature from DegreesDelisle. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesDelisle(double degreesdelisle) -#else - public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) -#endif - { - double value = (double) degreesdelisle; - return new Temperature(value, TemperatureUnit.DegreeDelisle); - } - - /// - /// Get Temperature from DegreesFahrenheit. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) -#else - public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) -#endif - { - double value = (double) degreesfahrenheit; - return new Temperature(value, TemperatureUnit.DegreeFahrenheit); - } - - /// - /// Get Temperature from DegreesNewton. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesNewton(double degreesnewton) -#else - public static Temperature FromDegreesNewton(QuantityValue degreesnewton) -#endif - { - double value = (double) degreesnewton; - return new Temperature(value, TemperatureUnit.DegreeNewton); - } - - /// - /// Get Temperature from DegreesRankine. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRankine(double degreesrankine) -#else - public static Temperature FromDegreesRankine(QuantityValue degreesrankine) -#endif - { - double value = (double) degreesrankine; - return new Temperature(value, TemperatureUnit.DegreeRankine); - } - - /// - /// Get Temperature from DegreesReaumur. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesReaumur(double degreesreaumur) -#else - public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) -#endif - { - double value = (double) degreesreaumur; - return new Temperature(value, TemperatureUnit.DegreeReaumur); - } - - /// - /// Get Temperature from DegreesRoemer. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRoemer(double degreesroemer) -#else - public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) -#endif - { - double value = (double) degreesroemer; - return new Temperature(value, TemperatureUnit.DegreeRoemer); - } - - /// - /// Get Temperature from Kelvins. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromKelvins(double kelvins) -#else - public static Temperature FromKelvins(QuantityValue kelvins) -#endif - { - double value = (double) kelvins; - return new Temperature(value, TemperatureUnit.Kelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Temperature unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Temperature From(double value, TemperatureUnit fromUnit) -#else - public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) -#endif - { - return new Temperature((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Temperature)) throw new ArgumentException("Expected type Temperature.", nameof(obj)); - - return CompareTo((Temperature)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Temperature other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Temperature, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Temperature)) - return false; - - var objQuantity = (Temperature)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Temperature by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Temperature, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Temperature other, Temperature maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Temperature. - public override int GetHashCode() - { - return new { type = typeof(Temperature), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Temperature to another Temperature with the unit representation . - /// - /// A Temperature with the specified unit. - public Temperature ToUnit(TemperatureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Temperature(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureUnit.DegreeCelsius: return _value + 273.15; - case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; - case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; - case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; - case TemperatureUnit.DegreeRankine: return _value*5/9; - case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; - case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; - case TemperatureUnit.Kelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; - case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; - case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; - case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; - case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; - case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; - case TemperatureUnit.Kelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Temperature Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Temperature result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Kelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static TemperatureUnit ToStringDefaultUnit { get; set; } = TemperatureUnit.Kelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Temperature - /// - public static Temperature MaxValue => new Temperature(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Temperature - /// - public static Temperature MinValue => new Temperature(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Temperature.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Temperature.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs b/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs deleted file mode 100644 index a4da3cde72..0000000000 --- a/Common/GeneratedCode/Quantities/TemperatureChangeRate.Common.g.cs +++ /dev/null @@ -1,679 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class TemperatureChangeRate : IQuantity -#else - public partial struct TemperatureChangeRate : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureChangeRateUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static TemperatureChangeRate() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit DegreeCelsiusPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public TemperatureChangeRate(double degreescelsiuspersecond) - { - _value = Convert.ToDouble(degreescelsiuspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - TemperatureChangeRate(double numericValue, TemperatureChangeRateUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerSecond. - /// - /// Value assuming base unit DegreeCelsiusPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - TemperatureChangeRate(long degreescelsiuspersecond) : this(Convert.ToDouble(degreescelsiuspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerSecond. - /// - /// Value assuming base unit DegreeCelsiusPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - TemperatureChangeRate(decimal degreescelsiuspersecond) : this(Convert.ToDouble(degreescelsiuspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.TemperatureChangeRate; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the TemperatureChangeRate quantity. - /// - public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); - - /// - /// Get TemperatureChangeRate in CentidegreesCelsiusPerSecond. - /// - public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DecadegreesCelsiusPerSecond. - /// - public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DecidegreesCelsiusPerSecond. - /// - public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in DegreesCelsiusPerMinute. - /// - public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - - /// - /// Get TemperatureChangeRate in DegreesCelsiusPerSecond. - /// - public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in HectodegreesCelsiusPerSecond. - /// - public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in KilodegreesCelsiusPerSecond. - /// - public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in MicrodegreesCelsiusPerSecond. - /// - public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in MillidegreesCelsiusPerSecond. - /// - public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - - /// - /// Get TemperatureChangeRate in NanodegreesCelsiusPerSecond. - /// - public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. - /// - public static TemperatureChangeRate Zero => new TemperatureChangeRate(0, BaseUnit); - - /// - /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) -#endif - { - double value = (double) centidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) -#endif - { - double value = (double) decadegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) -#endif - { - double value = (double) decidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) -#else - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) -#endif - { - double value = (double) degreescelsiusperminute; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - } - - /// - /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) -#else - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) -#endif - { - double value = (double) degreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) -#endif - { - double value = (double) hectodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) -#endif - { - double value = (double) kilodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) -#endif - { - double value = (double) microdegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) -#endif - { - double value = (double) millidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - } - - /// - /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) -#else - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) -#endif - { - double value = (double) nanodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureChangeRate unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit fromUnit) -#else - public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) -#endif - { - return new TemperatureChangeRate((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is TemperatureChangeRate)) throw new ArgumentException("Expected type TemperatureChangeRate.", nameof(obj)); - - return CompareTo((TemperatureChangeRate)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(TemperatureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is TemperatureChangeRate)) - return false; - - var objQuantity = (TemperatureChangeRate)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another TemperatureChangeRate by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(TemperatureChangeRate, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(TemperatureChangeRate other, TemperatureChangeRate maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureChangeRate. - public override int GetHashCode() - { - return new { type = typeof(TemperatureChangeRate), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . - /// - /// A TemperatureChangeRate with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (_value) * 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (_value) * 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (_value) * 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return _value/60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return _value; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (_value) * 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (_value) * 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (_value) * 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (_value) * 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureChangeRateUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (baseUnitValue) / 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return baseUnitValue*60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return baseUnitValue; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (baseUnitValue) / 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (baseUnitValue) / 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is DegreeCelsiusPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static TemperatureChangeRateUnit ToStringDefaultUnit { get; set; } = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureChangeRateUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MaxValue => new TemperatureChangeRate(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MinValue => new TemperatureChangeRate(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => TemperatureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs b/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs deleted file mode 100644 index 2c5f5310eb..0000000000 --- a/Common/GeneratedCode/Quantities/TemperatureDelta.Common.g.cs +++ /dev/null @@ -1,820 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Difference between two temperatures. The conversions are different than for Temperature. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class TemperatureDelta : IQuantity -#else - public partial struct TemperatureDelta : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureDeltaUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static TemperatureDelta() - { - } - - /// - /// Creates the quantity with the given value in the base unit Kelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public TemperatureDelta(double kelvins) - { - _value = Convert.ToDouble(kelvins); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - TemperatureDelta(double numericValue, TemperatureDeltaUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit Kelvin. - /// - /// Value assuming base unit Kelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - TemperatureDelta(long kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit Kelvin. - /// - /// Value assuming base unit Kelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - TemperatureDelta(decimal kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.TemperatureDelta; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the TemperatureDelta quantity. - /// - public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); - - /// - /// Get TemperatureDelta in DegreesCelsius. - /// - public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); - - /// - /// Get TemperatureDelta in DegreesCelsiusDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeCelsius instead")] - public double DegreesCelsiusDelta => As(TemperatureDeltaUnit.DegreeCelsiusDelta); - - /// - /// Get TemperatureDelta in DegreesDelisle. - /// - public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); - - /// - /// Get TemperatureDelta in DegreesDelisleDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeDelisle instead")] - public double DegreesDelisleDelta => As(TemperatureDeltaUnit.DegreeDelisleDelta); - - /// - /// Get TemperatureDelta in DegreesFahrenheit. - /// - public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); - - /// - /// Get TemperatureDelta in DegreesFahrenheitDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeFahrenheit instead")] - public double DegreesFahrenheitDelta => As(TemperatureDeltaUnit.DegreeFahrenheitDelta); - - /// - /// Get TemperatureDelta in DegreesNewton. - /// - public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); - - /// - /// Get TemperatureDelta in DegreesNewtonDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeNewton instead")] - public double DegreesNewtonDelta => As(TemperatureDeltaUnit.DegreeNewtonDelta); - - /// - /// Get TemperatureDelta in DegreesRankine. - /// - public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); - - /// - /// Get TemperatureDelta in DegreesRankineDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRankine instead")] - public double DegreesRankineDelta => As(TemperatureDeltaUnit.DegreeRankineDelta); - - /// - /// Get TemperatureDelta in DegreesReaumur. - /// - public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); - - /// - /// Get TemperatureDelta in DegreesReaumurDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeReaumur instead")] - public double DegreesReaumurDelta => As(TemperatureDeltaUnit.DegreeReaumurDelta); - - /// - /// Get TemperatureDelta in DegreesRoemer. - /// - public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); - - /// - /// Get TemperatureDelta in DegreesRoemerDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRoemer instead")] - public double DegreesRoemerDelta => As(TemperatureDeltaUnit.DegreeRoemerDelta); - - /// - /// Get TemperatureDelta in Kelvins. - /// - public double Kelvins => As(TemperatureDeltaUnit.Kelvin); - - /// - /// Get TemperatureDelta in KelvinsDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use Kelvin instead")] - public double KelvinsDelta => As(TemperatureDeltaUnit.KelvinDelta); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static TemperatureDelta Zero => new TemperatureDelta(0, BaseUnit); - - /// - /// Get TemperatureDelta from DegreesCelsius. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesCelsius(double degreescelsius) -#else - public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) -#endif - { - double value = (double) degreescelsius; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); - } - - /// - /// Get TemperatureDelta from DegreesCelsiusDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeCelsius instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesCelsiusDelta(double degreescelsiusdelta) -#else - public static TemperatureDelta FromDegreesCelsiusDelta(QuantityValue degreescelsiusdelta) -#endif - { - double value = (double) degreescelsiusdelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsiusDelta); - } - - /// - /// Get TemperatureDelta from DegreesDelisle. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) -#else - public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) -#endif - { - double value = (double) degreesdelisle; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); - } - - /// - /// Get TemperatureDelta from DegreesDelisleDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeDelisle instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesDelisleDelta(double degreesdelisledelta) -#else - public static TemperatureDelta FromDegreesDelisleDelta(QuantityValue degreesdelisledelta) -#endif - { - double value = (double) degreesdelisledelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisleDelta); - } - - /// - /// Get TemperatureDelta from DegreesFahrenheit. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) -#else - public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) -#endif - { - double value = (double) degreesfahrenheit; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); - } - - /// - /// Get TemperatureDelta from DegreesFahrenheitDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeFahrenheit instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesFahrenheitDelta(double degreesfahrenheitdelta) -#else - public static TemperatureDelta FromDegreesFahrenheitDelta(QuantityValue degreesfahrenheitdelta) -#endif - { - double value = (double) degreesfahrenheitdelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheitDelta); - } - - /// - /// Get TemperatureDelta from DegreesNewton. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesNewton(double degreesnewton) -#else - public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) -#endif - { - double value = (double) degreesnewton; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); - } - - /// - /// Get TemperatureDelta from DegreesNewtonDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeNewton instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesNewtonDelta(double degreesnewtondelta) -#else - public static TemperatureDelta FromDegreesNewtonDelta(QuantityValue degreesnewtondelta) -#endif - { - double value = (double) degreesnewtondelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewtonDelta); - } - - /// - /// Get TemperatureDelta from DegreesRankine. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRankine(double degreesrankine) -#else - public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) -#endif - { - double value = (double) degreesrankine; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); - } - - /// - /// Get TemperatureDelta from DegreesRankineDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRankine instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRankineDelta(double degreesrankinedelta) -#else - public static TemperatureDelta FromDegreesRankineDelta(QuantityValue degreesrankinedelta) -#endif - { - double value = (double) degreesrankinedelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankineDelta); - } - - /// - /// Get TemperatureDelta from DegreesReaumur. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) -#else - public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) -#endif - { - double value = (double) degreesreaumur; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); - } - - /// - /// Get TemperatureDelta from DegreesReaumurDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeReaumur instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesReaumurDelta(double degreesreaumurdelta) -#else - public static TemperatureDelta FromDegreesReaumurDelta(QuantityValue degreesreaumurdelta) -#endif - { - double value = (double) degreesreaumurdelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumurDelta); - } - - /// - /// Get TemperatureDelta from DegreesRoemer. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRoemer(double degreesroemer) -#else - public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) -#endif - { - double value = (double) degreesroemer; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); - } - - /// - /// Get TemperatureDelta from DegreesRoemerDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRoemer instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRoemerDelta(double degreesroemerdelta) -#else - public static TemperatureDelta FromDegreesRoemerDelta(QuantityValue degreesroemerdelta) -#endif - { - double value = (double) degreesroemerdelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemerDelta); - } - - /// - /// Get TemperatureDelta from Kelvins. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromKelvins(double kelvins) -#else - public static TemperatureDelta FromKelvins(QuantityValue kelvins) -#endif - { - double value = (double) kelvins; - return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); - } - - /// - /// Get TemperatureDelta from KelvinsDelta. - /// - [System.Obsolete("Deprecated due to github issue #180, please use Kelvin instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromKelvinsDelta(double kelvinsdelta) -#else - public static TemperatureDelta FromKelvinsDelta(QuantityValue kelvinsdelta) -#endif - { - double value = (double) kelvinsdelta; - return new TemperatureDelta(value, TemperatureDeltaUnit.KelvinDelta); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureDelta unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) -#else - public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) -#endif - { - return new TemperatureDelta((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureDeltaUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is TemperatureDelta)) throw new ArgumentException("Expected type TemperatureDelta.", nameof(obj)); - - return CompareTo((TemperatureDelta)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(TemperatureDelta other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureDelta, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is TemperatureDelta)) - return false; - - var objQuantity = (TemperatureDelta)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another TemperatureDelta by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(TemperatureDelta, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(TemperatureDelta other, TemperatureDelta maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureDelta. - public override int GetHashCode() - { - return new { type = typeof(TemperatureDelta), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . - /// - /// A TemperatureDelta with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureDelta(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return _value; - case TemperatureDeltaUnit.DegreeCelsiusDelta: return _value; - case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; - case TemperatureDeltaUnit.DegreeDelisleDelta: return _value*-2/3; - case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; - case TemperatureDeltaUnit.DegreeFahrenheitDelta: return _value*5/9; - case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; - case TemperatureDeltaUnit.DegreeNewtonDelta: return _value*100/33; - case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; - case TemperatureDeltaUnit.DegreeRankineDelta: return _value*5/9; - case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; - case TemperatureDeltaUnit.DegreeReaumurDelta: return _value*5/4; - case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; - case TemperatureDeltaUnit.DegreeRoemerDelta: return _value*40/21; - case TemperatureDeltaUnit.Kelvin: return _value; - case TemperatureDeltaUnit.KelvinDelta: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureDeltaUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; - case TemperatureDeltaUnit.DegreeCelsiusDelta: return baseUnitValue; - case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; - case TemperatureDeltaUnit.DegreeDelisleDelta: return baseUnitValue*-3/2; - case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeFahrenheitDelta: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; - case TemperatureDeltaUnit.DegreeNewtonDelta: return baseUnitValue*33/100; - case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeRankineDelta: return baseUnitValue*9/5; - case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; - case TemperatureDeltaUnit.DegreeReaumurDelta: return baseUnitValue*4/5; - case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; - case TemperatureDeltaUnit.DegreeRoemerDelta: return baseUnitValue*21/40; - case TemperatureDeltaUnit.Kelvin: return baseUnitValue; - case TemperatureDeltaUnit.KelvinDelta: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureDelta Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureDeltaUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is Kelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static TemperatureDeltaUnit ToStringDefaultUnit { get; set; } = TemperatureDeltaUnit.Kelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TemperatureDeltaUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of TemperatureDelta - /// - public static TemperatureDelta MaxValue => new TemperatureDelta(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of TemperatureDelta - /// - public static TemperatureDelta MinValue => new TemperatureDelta(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => TemperatureDelta.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs b/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs deleted file mode 100644 index 59ddee2a84..0000000000 --- a/Common/GeneratedCode/Quantities/ThermalConductivity.Common.g.cs +++ /dev/null @@ -1,511 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Thermal conductivity is the property of a material to conduct heat. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ThermalConductivity : IQuantity -#else - public partial struct ThermalConductivity : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalConductivityUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ThermalConductivity() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit WattPerMeterKelvin. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ThermalConductivity(double wattspermeterkelvin) - { - _value = Convert.ToDouble(wattspermeterkelvin); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ThermalConductivity(double numericValue, ThermalConductivityUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit WattPerMeterKelvin. - /// - /// Value assuming base unit WattPerMeterKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ThermalConductivity(long wattspermeterkelvin) : this(Convert.ToDouble(wattspermeterkelvin), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit WattPerMeterKelvin. - /// - /// Value assuming base unit WattPerMeterKelvin. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ThermalConductivity(decimal wattspermeterkelvin) : this(Convert.ToDouble(wattspermeterkelvin), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ThermalConductivity; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ThermalConductivity quantity. - /// - public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); - - /// - /// Get ThermalConductivity in BtusPerHourFootFahrenheit. - /// - public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); - - /// - /// Get ThermalConductivity in WattsPerMeterKelvin. - /// - public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. - /// - public static ThermalConductivity Zero => new ThermalConductivity(0, BaseUnit); - - /// - /// Get ThermalConductivity from BtusPerHourFootFahrenheit. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromBtusPerHourFootFahrenheit(double btusperhourfootfahrenheit) -#else - public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) -#endif - { - double value = (double) btusperhourfootfahrenheit; - return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); - } - - /// - /// Get ThermalConductivity from WattsPerMeterKelvin. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) -#else - public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) -#endif - { - double value = (double) wattspermeterkelvin; - return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalConductivity unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalConductivity From(double value, ThermalConductivityUnit fromUnit) -#else - public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) -#endif - { - return new ThermalConductivity((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ThermalConductivity)) throw new ArgumentException("Expected type ThermalConductivity.", nameof(obj)); - - return CompareTo((ThermalConductivity)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ThermalConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ThermalConductivity)) - return false; - - var objQuantity = (ThermalConductivity)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ThermalConductivity by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ThermalConductivity, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ThermalConductivity other, ThermalConductivity maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalConductivity. - public override int GetHashCode() - { - return new { type = typeof(ThermalConductivity), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . - /// - /// A ThermalConductivity with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return _value*1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalConductivityUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return baseUnitValue/1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalConductivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalConductivityUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is WattPerMeterKelvin - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ThermalConductivityUnit ToStringDefaultUnit { get; set; } = ThermalConductivityUnit.WattPerMeterKelvin; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ThermalConductivityUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ThermalConductivity - /// - public static ThermalConductivity MaxValue => new ThermalConductivity(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ThermalConductivity - /// - public static ThermalConductivity MinValue => new ThermalConductivity(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ThermalConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs b/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs deleted file mode 100644 index d0c4034f11..0000000000 --- a/Common/GeneratedCode/Quantities/ThermalResistance.Common.g.cs +++ /dev/null @@ -1,574 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class ThermalResistance : IQuantity -#else - public partial struct ThermalResistance : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalResistanceUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static ThermalResistance() - { - BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit SquareMeterKelvinPerKilowatt. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public ThermalResistance(double squaremeterkelvinsperkilowatt) - { - _value = Convert.ToDouble(squaremeterkelvinsperkilowatt); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - ThermalResistance(double numericValue, ThermalResistanceUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit SquareMeterKelvinPerKilowatt. - /// - /// Value assuming base unit SquareMeterKelvinPerKilowatt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ThermalResistance(long squaremeterkelvinsperkilowatt) : this(Convert.ToDouble(squaremeterkelvinsperkilowatt), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit SquareMeterKelvinPerKilowatt. - /// - /// Value assuming base unit SquareMeterKelvinPerKilowatt. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - ThermalResistance(decimal squaremeterkelvinsperkilowatt) : this(Convert.ToDouble(squaremeterkelvinsperkilowatt), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.ThermalResistance; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the ThermalResistance quantity. - /// - public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); - - /// - /// Get ThermalResistance in HourSquareFeetDegreesFahrenheitPerBtu. - /// - public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - - /// - /// Get ThermalResistance in SquareCentimeterHourDegreesCelsiusPerKilocalorie. - /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - - /// - /// Get ThermalResistance in SquareCentimeterKelvinsPerWatt. - /// - public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - - /// - /// Get ThermalResistance in SquareMeterDegreesCelsiusPerWatt. - /// - public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - - /// - /// Get ThermalResistance in SquareMeterKelvinsPerKilowatt. - /// - public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. - /// - public static ThermalResistance Zero => new ThermalResistance(0, BaseUnit); - - /// - /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) -#else - public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) -#endif - { - double value = (double) hoursquarefeetdegreesfahrenheitperbtu; - return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - } - - /// - /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) -#else - public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) -#endif - { - double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - } - - /// - /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) -#else - public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) -#endif - { - double value = (double) squarecentimeterkelvinsperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - } - - /// - /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) -#else - public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) -#endif - { - double value = (double) squaremeterdegreescelsiusperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - } - - /// - /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) -#else - public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) -#endif - { - double value = (double) squaremeterkelvinsperkilowatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalResistance unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) -#else - public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) -#endif - { - return new ThermalResistance((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is ThermalResistance)) throw new ArgumentException("Expected type ThermalResistance.", nameof(obj)); - - return CompareTo((ThermalResistance)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(ThermalResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is ThermalResistance)) - return false; - - var objQuantity = (ThermalResistance)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another ThermalResistance by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(ThermalResistance, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(ThermalResistance other, ThermalResistance maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalResistance. - public override int GetHashCode() - { - return new { type = typeof(ThermalResistance), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalResistance to another ThermalResistance with the unit representation . - /// - /// A ThermalResistance with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalResistanceUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalResistance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalResistance result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalResistanceUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is SquareMeterKelvinPerKilowatt - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static ThermalResistanceUnit ToStringDefaultUnit { get; set; } = ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(ThermalResistanceUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of ThermalResistance - /// - public static ThermalResistance MaxValue => new ThermalResistance(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of ThermalResistance - /// - public static ThermalResistance MinValue => new ThermalResistance(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => ThermalResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Torque.Common.g.cs b/Common/GeneratedCode/Quantities/Torque.Common.g.cs deleted file mode 100644 index 6f9df627ee..0000000000 --- a/Common/GeneratedCode/Quantities/Torque.Common.g.cs +++ /dev/null @@ -1,910 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Torque : IQuantity -#else - public partial struct Torque : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TorqueUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Torque() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit NewtonMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Torque(double newtonmeters) - { - _value = Convert.ToDouble(newtonmeters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Torque(double numericValue, TorqueUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeter. - /// - /// Value assuming base unit NewtonMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Torque(long newtonmeters) : this(Convert.ToDouble(newtonmeters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit NewtonMeter. - /// - /// Value assuming base unit NewtonMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Torque(decimal newtonmeters) : this(Convert.ToDouble(newtonmeters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Torque; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Torque quantity. - /// - public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); - - /// - /// Get Torque in KilogramForceCentimeters. - /// - public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); - - /// - /// Get Torque in KilogramForceMeters. - /// - public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); - - /// - /// Get Torque in KilogramForceMillimeters. - /// - public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); - - /// - /// Get Torque in KilonewtonCentimeters. - /// - public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); - - /// - /// Get Torque in KilonewtonMeters. - /// - public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); - - /// - /// Get Torque in KilonewtonMillimeters. - /// - public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); - - /// - /// Get Torque in KilopoundForceFeet. - /// - public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); - - /// - /// Get Torque in KilopoundForceInches. - /// - public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); - - /// - /// Get Torque in MeganewtonCentimeters. - /// - public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); - - /// - /// Get Torque in MeganewtonMeters. - /// - public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); - - /// - /// Get Torque in MeganewtonMillimeters. - /// - public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); - - /// - /// Get Torque in MegapoundForceFeet. - /// - public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); - - /// - /// Get Torque in MegapoundForceInches. - /// - public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); - - /// - /// Get Torque in NewtonCentimeters. - /// - public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); - - /// - /// Get Torque in NewtonMeters. - /// - public double NewtonMeters => As(TorqueUnit.NewtonMeter); - - /// - /// Get Torque in NewtonMillimeters. - /// - public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); - - /// - /// Get Torque in PoundForceFeet. - /// - public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); - - /// - /// Get Torque in PoundForceInches. - /// - public double PoundForceInches => As(TorqueUnit.PoundForceInch); - - /// - /// Get Torque in TonneForceCentimeters. - /// - public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); - - /// - /// Get Torque in TonneForceMeters. - /// - public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); - - /// - /// Get Torque in TonneForceMillimeters. - /// - public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. - /// - public static Torque Zero => new Torque(0, BaseUnit); - - /// - /// Get Torque from KilogramForceCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) -#else - public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) -#endif - { - double value = (double) kilogramforcecentimeters; - return new Torque(value, TorqueUnit.KilogramForceCentimeter); - } - - /// - /// Get Torque from KilogramForceMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMeters(double kilogramforcemeters) -#else - public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) -#endif - { - double value = (double) kilogramforcemeters; - return new Torque(value, TorqueUnit.KilogramForceMeter); - } - - /// - /// Get Torque from KilogramForceMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) -#else - public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) -#endif - { - double value = (double) kilogramforcemillimeters; - return new Torque(value, TorqueUnit.KilogramForceMillimeter); - } - - /// - /// Get Torque from KilonewtonCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) -#else - public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) -#endif - { - double value = (double) kilonewtoncentimeters; - return new Torque(value, TorqueUnit.KilonewtonCentimeter); - } - - /// - /// Get Torque from KilonewtonMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMeters(double kilonewtonmeters) -#else - public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) -#endif - { - double value = (double) kilonewtonmeters; - return new Torque(value, TorqueUnit.KilonewtonMeter); - } - - /// - /// Get Torque from KilonewtonMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) -#else - public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) -#endif - { - double value = (double) kilonewtonmillimeters; - return new Torque(value, TorqueUnit.KilonewtonMillimeter); - } - - /// - /// Get Torque from KilopoundForceFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) -#else - public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) -#endif - { - double value = (double) kilopoundforcefeet; - return new Torque(value, TorqueUnit.KilopoundForceFoot); - } - - /// - /// Get Torque from KilopoundForceInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceInches(double kilopoundforceinches) -#else - public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) -#endif - { - double value = (double) kilopoundforceinches; - return new Torque(value, TorqueUnit.KilopoundForceInch); - } - - /// - /// Get Torque from MeganewtonCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) -#else - public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) -#endif - { - double value = (double) meganewtoncentimeters; - return new Torque(value, TorqueUnit.MeganewtonCentimeter); - } - - /// - /// Get Torque from MeganewtonMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMeters(double meganewtonmeters) -#else - public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) -#endif - { - double value = (double) meganewtonmeters; - return new Torque(value, TorqueUnit.MeganewtonMeter); - } - - /// - /// Get Torque from MeganewtonMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) -#else - public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) -#endif - { - double value = (double) meganewtonmillimeters; - return new Torque(value, TorqueUnit.MeganewtonMillimeter); - } - - /// - /// Get Torque from MegapoundForceFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceFeet(double megapoundforcefeet) -#else - public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) -#endif - { - double value = (double) megapoundforcefeet; - return new Torque(value, TorqueUnit.MegapoundForceFoot); - } - - /// - /// Get Torque from MegapoundForceInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceInches(double megapoundforceinches) -#else - public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) -#endif - { - double value = (double) megapoundforceinches; - return new Torque(value, TorqueUnit.MegapoundForceInch); - } - - /// - /// Get Torque from NewtonCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonCentimeters(double newtoncentimeters) -#else - public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) -#endif - { - double value = (double) newtoncentimeters; - return new Torque(value, TorqueUnit.NewtonCentimeter); - } - - /// - /// Get Torque from NewtonMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMeters(double newtonmeters) -#else - public static Torque FromNewtonMeters(QuantityValue newtonmeters) -#endif - { - double value = (double) newtonmeters; - return new Torque(value, TorqueUnit.NewtonMeter); - } - - /// - /// Get Torque from NewtonMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMillimeters(double newtonmillimeters) -#else - public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) -#endif - { - double value = (double) newtonmillimeters; - return new Torque(value, TorqueUnit.NewtonMillimeter); - } - - /// - /// Get Torque from PoundForceFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceFeet(double poundforcefeet) -#else - public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) -#endif - { - double value = (double) poundforcefeet; - return new Torque(value, TorqueUnit.PoundForceFoot); - } - - /// - /// Get Torque from PoundForceInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceInches(double poundforceinches) -#else - public static Torque FromPoundForceInches(QuantityValue poundforceinches) -#endif - { - double value = (double) poundforceinches; - return new Torque(value, TorqueUnit.PoundForceInch); - } - - /// - /// Get Torque from TonneForceCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) -#else - public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) -#endif - { - double value = (double) tonneforcecentimeters; - return new Torque(value, TorqueUnit.TonneForceCentimeter); - } - - /// - /// Get Torque from TonneForceMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMeters(double tonneforcemeters) -#else - public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) -#endif - { - double value = (double) tonneforcemeters; - return new Torque(value, TorqueUnit.TonneForceMeter); - } - - /// - /// Get Torque from TonneForceMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) -#else - public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) -#endif - { - double value = (double) tonneforcemillimeters; - return new Torque(value, TorqueUnit.TonneForceMillimeter); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Torque unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Torque From(double value, TorqueUnit fromUnit) -#else - public static Torque From(QuantityValue value, TorqueUnit fromUnit) -#endif - { - return new Torque((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TorqueUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Torque)) throw new ArgumentException("Expected type Torque.", nameof(obj)); - - return CompareTo((Torque)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Torque other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Torque, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Torque)) - return false; - - var objQuantity = (Torque)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Torque by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Torque, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Torque other, Torque maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Torque. - public override int GetHashCode() - { - return new { type = typeof(Torque), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorqueUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Torque to another Torque with the unit representation . - /// - /// A Torque with the specified unit. - public Torque ToUnit(TorqueUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Torque(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TorqueUnit.KilogramForceCentimeter: return _value*0.0980665019960652; - case TorqueUnit.KilogramForceMeter: return _value*9.80665019960652; - case TorqueUnit.KilogramForceMillimeter: return _value*0.00980665019960652; - case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; - case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; - case TorqueUnit.KilopoundForceFoot: return (_value*1.3558179483314) * 1e3d; - case TorqueUnit.KilopoundForceInch: return (_value*1.129848290276167e-1) * 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; - case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; - case TorqueUnit.MegapoundForceFoot: return (_value*1.3558179483314) * 1e6d; - case TorqueUnit.MegapoundForceInch: return (_value*1.129848290276167e-1) * 1e6d; - case TorqueUnit.NewtonCentimeter: return _value*0.01; - case TorqueUnit.NewtonMeter: return _value; - case TorqueUnit.NewtonMillimeter: return _value*0.001; - case TorqueUnit.PoundForceFoot: return _value*1.3558179483314; - case TorqueUnit.PoundForceInch: return _value*1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return _value*98.0665019960652; - case TorqueUnit.TonneForceMeter: return _value*9806.65019960653; - case TorqueUnit.TonneForceMillimeter: return _value*9.80665019960652; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TorqueUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TorqueUnit.KilogramForceCentimeter: return baseUnitValue*10.1971619222242; - case TorqueUnit.KilogramForceMeter: return baseUnitValue*0.101971619222242; - case TorqueUnit.KilogramForceMillimeter: return baseUnitValue*101.971619222242; - case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; - case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; - case TorqueUnit.KilopoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e3d; - case TorqueUnit.KilopoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; - case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; - case TorqueUnit.MegapoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e6d; - case TorqueUnit.MegapoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e6d; - case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; - case TorqueUnit.NewtonMeter: return baseUnitValue; - case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; - case TorqueUnit.PoundForceFoot: return baseUnitValue/1.3558179483314; - case TorqueUnit.PoundForceInch: return baseUnitValue/1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return baseUnitValue*0.0101971619222242; - case TorqueUnit.TonneForceMeter: return baseUnitValue*0.000101971619222242; - case TorqueUnit.TonneForceMillimeter: return baseUnitValue*0.101971619222242; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Torque Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Torque result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TorqueUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is NewtonMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static TorqueUnit ToStringDefaultUnit { get; set; } = TorqueUnit.NewtonMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(TorqueUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Torque - /// - public static Torque MaxValue => new Torque(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Torque - /// - public static Torque MinValue => new Torque(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Torque.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Torque.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs b/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs deleted file mode 100644 index eaed4be5ac..0000000000 --- a/Common/GeneratedCode/Quantities/VitaminA.Common.g.cs +++ /dev/null @@ -1,489 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class VitaminA : IQuantity -#else - public partial struct VitaminA : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VitaminAUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static VitaminA() - { - } - - /// - /// Creates the quantity with the given value in the base unit InternationalUnit. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public VitaminA(double internationalunits) - { - _value = Convert.ToDouble(internationalunits); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - VitaminA(double numericValue, VitaminAUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit InternationalUnit. - /// - /// Value assuming base unit InternationalUnit. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - VitaminA(long internationalunits) : this(Convert.ToDouble(internationalunits), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit InternationalUnit. - /// - /// Value assuming base unit InternationalUnit. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - VitaminA(decimal internationalunits) : this(Convert.ToDouble(internationalunits), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.VitaminA; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the VitaminA quantity. - /// - public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); - - /// - /// Get VitaminA in InternationalUnits. - /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. - /// - public static VitaminA Zero => new VitaminA(0, BaseUnit); - - /// - /// Get VitaminA from InternationalUnits. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VitaminA FromInternationalUnits(double internationalunits) -#else - public static VitaminA FromInternationalUnits(QuantityValue internationalunits) -#endif - { - double value = (double) internationalunits; - return new VitaminA(value, VitaminAUnit.InternationalUnit); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VitaminA unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VitaminA From(double value, VitaminAUnit fromUnit) -#else - public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) -#endif - { - return new VitaminA((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VitaminAUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is VitaminA)) throw new ArgumentException("Expected type VitaminA.", nameof(obj)); - - return CompareTo((VitaminA)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(VitaminA other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VitaminA, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is VitaminA)) - return false; - - var objQuantity = (VitaminA)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another VitaminA by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(VitaminA, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(VitaminA other, VitaminA maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VitaminA. - public override int GetHashCode() - { - return new { type = typeof(VitaminA), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VitaminAUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VitaminA to another VitaminA with the unit representation . - /// - /// A VitaminA with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VitaminA(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VitaminAUnit.InternationalUnit: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VitaminAUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VitaminAUnit.InternationalUnit: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VitaminA Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VitaminA result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VitaminAUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is InternationalUnit - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static VitaminAUnit ToStringDefaultUnit { get; set; } = VitaminAUnit.InternationalUnit; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VitaminAUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of VitaminA - /// - public static VitaminA MaxValue => new VitaminA(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of VitaminA - /// - public static VitaminA MinValue => new VitaminA(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => VitaminA.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VitaminA.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/Volume.Common.g.cs b/Common/GeneratedCode/Quantities/Volume.Common.g.cs deleted file mode 100644 index 65a8d010b2..0000000000 --- a/Common/GeneratedCode/Quantities/Volume.Common.g.cs +++ /dev/null @@ -1,1418 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Volume : IQuantity -#else - public partial struct Volume : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static Volume() - { - BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit CubicMeter. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public Volume(double cubicmeters) - { - _value = Convert.ToDouble(cubicmeters); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - Volume(double numericValue, VolumeUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit CubicMeter. - /// - /// Value assuming base unit CubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Volume(long cubicmeters) : this(Convert.ToDouble(cubicmeters), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit CubicMeter. - /// - /// Value assuming base unit CubicMeter. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - Volume(decimal cubicmeters) : this(Convert.ToDouble(cubicmeters), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.Volume; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the Volume quantity. - /// - public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); - - /// - /// Get Volume in AuTablespoons. - /// - public double AuTablespoons => As(VolumeUnit.AuTablespoon); - - /// - /// Get Volume in Centiliters. - /// - public double Centiliters => As(VolumeUnit.Centiliter); - - /// - /// Get Volume in CubicCentimeters. - /// - public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); - - /// - /// Get Volume in CubicDecimeters. - /// - public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); - - /// - /// Get Volume in CubicFeet. - /// - public double CubicFeet => As(VolumeUnit.CubicFoot); - - /// - /// Get Volume in CubicInches. - /// - public double CubicInches => As(VolumeUnit.CubicInch); - - /// - /// Get Volume in CubicKilometers. - /// - public double CubicKilometers => As(VolumeUnit.CubicKilometer); - - /// - /// Get Volume in CubicMeters. - /// - public double CubicMeters => As(VolumeUnit.CubicMeter); - - /// - /// Get Volume in CubicMicrometers. - /// - public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); - - /// - /// Get Volume in CubicMiles. - /// - public double CubicMiles => As(VolumeUnit.CubicMile); - - /// - /// Get Volume in CubicMillimeters. - /// - public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); - - /// - /// Get Volume in CubicYards. - /// - public double CubicYards => As(VolumeUnit.CubicYard); - - /// - /// Get Volume in Deciliters. - /// - public double Deciliters => As(VolumeUnit.Deciliter); - - /// - /// Get Volume in HectocubicFeet. - /// - public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); - - /// - /// Get Volume in HectocubicMeters. - /// - public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); - - /// - /// Get Volume in Hectoliters. - /// - public double Hectoliters => As(VolumeUnit.Hectoliter); - - /// - /// Get Volume in ImperialBeerBarrels. - /// - public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); - - /// - /// Get Volume in ImperialGallons. - /// - public double ImperialGallons => As(VolumeUnit.ImperialGallon); - - /// - /// Get Volume in ImperialOunces. - /// - public double ImperialOunces => As(VolumeUnit.ImperialOunce); - - /// - /// Get Volume in KilocubicFeet. - /// - public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); - - /// - /// Get Volume in KilocubicMeters. - /// - public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); - - /// - /// Get Volume in KiloimperialGallons. - /// - public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); - - /// - /// Get Volume in Kiloliters. - /// - public double Kiloliters => As(VolumeUnit.Kiloliter); - - /// - /// Get Volume in KilousGallons. - /// - public double KilousGallons => As(VolumeUnit.KilousGallon); - - /// - /// Get Volume in Liters. - /// - public double Liters => As(VolumeUnit.Liter); - - /// - /// Get Volume in MegacubicFeet. - /// - public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); - - /// - /// Get Volume in MegaimperialGallons. - /// - public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); - - /// - /// Get Volume in MegausGallons. - /// - public double MegausGallons => As(VolumeUnit.MegausGallon); - - /// - /// Get Volume in MetricCups. - /// - public double MetricCups => As(VolumeUnit.MetricCup); - - /// - /// Get Volume in MetricTeaspoons. - /// - public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); - - /// - /// Get Volume in Microliters. - /// - public double Microliters => As(VolumeUnit.Microliter); - - /// - /// Get Volume in Milliliters. - /// - public double Milliliters => As(VolumeUnit.Milliliter); - - /// - /// Get Volume in OilBarrels. - /// - public double OilBarrels => As(VolumeUnit.OilBarrel); - - /// - /// Get Volume in Tablespoons. - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTablespoon instead")] - public double Tablespoons => As(VolumeUnit.Tablespoon); - - /// - /// Get Volume in Teaspoons. - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTeaspoon instead")] - public double Teaspoons => As(VolumeUnit.Teaspoon); - - /// - /// Get Volume in UkTablespoons. - /// - public double UkTablespoons => As(VolumeUnit.UkTablespoon); - - /// - /// Get Volume in UsBeerBarrels. - /// - public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); - - /// - /// Get Volume in UsCustomaryCups. - /// - public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); - - /// - /// Get Volume in UsGallons. - /// - public double UsGallons => As(VolumeUnit.UsGallon); - - /// - /// Get Volume in UsLegalCups. - /// - public double UsLegalCups => As(VolumeUnit.UsLegalCup); - - /// - /// Get Volume in UsOunces. - /// - public double UsOunces => As(VolumeUnit.UsOunce); - - /// - /// Get Volume in UsPints. - /// - public double UsPints => As(VolumeUnit.UsPint); - - /// - /// Get Volume in UsQuarts. - /// - public double UsQuarts => As(VolumeUnit.UsQuart); - - /// - /// Get Volume in UsTablespoons. - /// - public double UsTablespoons => As(VolumeUnit.UsTablespoon); - - /// - /// Get Volume in UsTeaspoons. - /// - public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. - /// - public static Volume Zero => new Volume(0, BaseUnit); - - /// - /// Get Volume from AuTablespoons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromAuTablespoons(double autablespoons) -#else - public static Volume FromAuTablespoons(QuantityValue autablespoons) -#endif - { - double value = (double) autablespoons; - return new Volume(value, VolumeUnit.AuTablespoon); - } - - /// - /// Get Volume from Centiliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCentiliters(double centiliters) -#else - public static Volume FromCentiliters(QuantityValue centiliters) -#endif - { - double value = (double) centiliters; - return new Volume(value, VolumeUnit.Centiliter); - } - - /// - /// Get Volume from CubicCentimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicCentimeters(double cubiccentimeters) -#else - public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) -#endif - { - double value = (double) cubiccentimeters; - return new Volume(value, VolumeUnit.CubicCentimeter); - } - - /// - /// Get Volume from CubicDecimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicDecimeters(double cubicdecimeters) -#else - public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) -#endif - { - double value = (double) cubicdecimeters; - return new Volume(value, VolumeUnit.CubicDecimeter); - } - - /// - /// Get Volume from CubicFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicFeet(double cubicfeet) -#else - public static Volume FromCubicFeet(QuantityValue cubicfeet) -#endif - { - double value = (double) cubicfeet; - return new Volume(value, VolumeUnit.CubicFoot); - } - - /// - /// Get Volume from CubicInches. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicInches(double cubicinches) -#else - public static Volume FromCubicInches(QuantityValue cubicinches) -#endif - { - double value = (double) cubicinches; - return new Volume(value, VolumeUnit.CubicInch); - } - - /// - /// Get Volume from CubicKilometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicKilometers(double cubickilometers) -#else - public static Volume FromCubicKilometers(QuantityValue cubickilometers) -#endif - { - double value = (double) cubickilometers; - return new Volume(value, VolumeUnit.CubicKilometer); - } - - /// - /// Get Volume from CubicMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMeters(double cubicmeters) -#else - public static Volume FromCubicMeters(QuantityValue cubicmeters) -#endif - { - double value = (double) cubicmeters; - return new Volume(value, VolumeUnit.CubicMeter); - } - - /// - /// Get Volume from CubicMicrometers. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMicrometers(double cubicmicrometers) -#else - public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) -#endif - { - double value = (double) cubicmicrometers; - return new Volume(value, VolumeUnit.CubicMicrometer); - } - - /// - /// Get Volume from CubicMiles. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMiles(double cubicmiles) -#else - public static Volume FromCubicMiles(QuantityValue cubicmiles) -#endif - { - double value = (double) cubicmiles; - return new Volume(value, VolumeUnit.CubicMile); - } - - /// - /// Get Volume from CubicMillimeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMillimeters(double cubicmillimeters) -#else - public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) -#endif - { - double value = (double) cubicmillimeters; - return new Volume(value, VolumeUnit.CubicMillimeter); - } - - /// - /// Get Volume from CubicYards. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicYards(double cubicyards) -#else - public static Volume FromCubicYards(QuantityValue cubicyards) -#endif - { - double value = (double) cubicyards; - return new Volume(value, VolumeUnit.CubicYard); - } - - /// - /// Get Volume from Deciliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDeciliters(double deciliters) -#else - public static Volume FromDeciliters(QuantityValue deciliters) -#endif - { - double value = (double) deciliters; - return new Volume(value, VolumeUnit.Deciliter); - } - - /// - /// Get Volume from HectocubicFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicFeet(double hectocubicfeet) -#else - public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) -#endif - { - double value = (double) hectocubicfeet; - return new Volume(value, VolumeUnit.HectocubicFoot); - } - - /// - /// Get Volume from HectocubicMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicMeters(double hectocubicmeters) -#else - public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) -#endif - { - double value = (double) hectocubicmeters; - return new Volume(value, VolumeUnit.HectocubicMeter); - } - - /// - /// Get Volume from Hectoliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectoliters(double hectoliters) -#else - public static Volume FromHectoliters(QuantityValue hectoliters) -#endif - { - double value = (double) hectoliters; - return new Volume(value, VolumeUnit.Hectoliter); - } - - /// - /// Get Volume from ImperialBeerBarrels. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) -#else - public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) -#endif - { - double value = (double) imperialbeerbarrels; - return new Volume(value, VolumeUnit.ImperialBeerBarrel); - } - - /// - /// Get Volume from ImperialGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialGallons(double imperialgallons) -#else - public static Volume FromImperialGallons(QuantityValue imperialgallons) -#endif - { - double value = (double) imperialgallons; - return new Volume(value, VolumeUnit.ImperialGallon); - } - - /// - /// Get Volume from ImperialOunces. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialOunces(double imperialounces) -#else - public static Volume FromImperialOunces(QuantityValue imperialounces) -#endif - { - double value = (double) imperialounces; - return new Volume(value, VolumeUnit.ImperialOunce); - } - - /// - /// Get Volume from KilocubicFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicFeet(double kilocubicfeet) -#else - public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) -#endif - { - double value = (double) kilocubicfeet; - return new Volume(value, VolumeUnit.KilocubicFoot); - } - - /// - /// Get Volume from KilocubicMeters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicMeters(double kilocubicmeters) -#else - public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) -#endif - { - double value = (double) kilocubicmeters; - return new Volume(value, VolumeUnit.KilocubicMeter); - } - - /// - /// Get Volume from KiloimperialGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKiloimperialGallons(double kiloimperialgallons) -#else - public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) -#endif - { - double value = (double) kiloimperialgallons; - return new Volume(value, VolumeUnit.KiloimperialGallon); - } - - /// - /// Get Volume from Kiloliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKiloliters(double kiloliters) -#else - public static Volume FromKiloliters(QuantityValue kiloliters) -#endif - { - double value = (double) kiloliters; - return new Volume(value, VolumeUnit.Kiloliter); - } - - /// - /// Get Volume from KilousGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilousGallons(double kilousgallons) -#else - public static Volume FromKilousGallons(QuantityValue kilousgallons) -#endif - { - double value = (double) kilousgallons; - return new Volume(value, VolumeUnit.KilousGallon); - } - - /// - /// Get Volume from Liters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromLiters(double liters) -#else - public static Volume FromLiters(QuantityValue liters) -#endif - { - double value = (double) liters; - return new Volume(value, VolumeUnit.Liter); - } - - /// - /// Get Volume from MegacubicFeet. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegacubicFeet(double megacubicfeet) -#else - public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) -#endif - { - double value = (double) megacubicfeet; - return new Volume(value, VolumeUnit.MegacubicFoot); - } - - /// - /// Get Volume from MegaimperialGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegaimperialGallons(double megaimperialgallons) -#else - public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) -#endif - { - double value = (double) megaimperialgallons; - return new Volume(value, VolumeUnit.MegaimperialGallon); - } - - /// - /// Get Volume from MegausGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegausGallons(double megausgallons) -#else - public static Volume FromMegausGallons(QuantityValue megausgallons) -#endif - { - double value = (double) megausgallons; - return new Volume(value, VolumeUnit.MegausGallon); - } - - /// - /// Get Volume from MetricCups. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricCups(double metriccups) -#else - public static Volume FromMetricCups(QuantityValue metriccups) -#endif - { - double value = (double) metriccups; - return new Volume(value, VolumeUnit.MetricCup); - } - - /// - /// Get Volume from MetricTeaspoons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricTeaspoons(double metricteaspoons) -#else - public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) -#endif - { - double value = (double) metricteaspoons; - return new Volume(value, VolumeUnit.MetricTeaspoon); - } - - /// - /// Get Volume from Microliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMicroliters(double microliters) -#else - public static Volume FromMicroliters(QuantityValue microliters) -#endif - { - double value = (double) microliters; - return new Volume(value, VolumeUnit.Microliter); - } - - /// - /// Get Volume from Milliliters. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMilliliters(double milliliters) -#else - public static Volume FromMilliliters(QuantityValue milliliters) -#endif - { - double value = (double) milliliters; - return new Volume(value, VolumeUnit.Milliliter); - } - - /// - /// Get Volume from OilBarrels. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromOilBarrels(double oilbarrels) -#else - public static Volume FromOilBarrels(QuantityValue oilbarrels) -#endif - { - double value = (double) oilbarrels; - return new Volume(value, VolumeUnit.OilBarrel); - } - - /// - /// Get Volume from Tablespoons. - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTablespoon instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromTablespoons(double tablespoons) -#else - public static Volume FromTablespoons(QuantityValue tablespoons) -#endif - { - double value = (double) tablespoons; - return new Volume(value, VolumeUnit.Tablespoon); - } - - /// - /// Get Volume from Teaspoons. - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTeaspoon instead")] -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromTeaspoons(double teaspoons) -#else - public static Volume FromTeaspoons(QuantityValue teaspoons) -#endif - { - double value = (double) teaspoons; - return new Volume(value, VolumeUnit.Teaspoon); - } - - /// - /// Get Volume from UkTablespoons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUkTablespoons(double uktablespoons) -#else - public static Volume FromUkTablespoons(QuantityValue uktablespoons) -#endif - { - double value = (double) uktablespoons; - return new Volume(value, VolumeUnit.UkTablespoon); - } - - /// - /// Get Volume from UsBeerBarrels. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsBeerBarrels(double usbeerbarrels) -#else - public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) -#endif - { - double value = (double) usbeerbarrels; - return new Volume(value, VolumeUnit.UsBeerBarrel); - } - - /// - /// Get Volume from UsCustomaryCups. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsCustomaryCups(double uscustomarycups) -#else - public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) -#endif - { - double value = (double) uscustomarycups; - return new Volume(value, VolumeUnit.UsCustomaryCup); - } - - /// - /// Get Volume from UsGallons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsGallons(double usgallons) -#else - public static Volume FromUsGallons(QuantityValue usgallons) -#endif - { - double value = (double) usgallons; - return new Volume(value, VolumeUnit.UsGallon); - } - - /// - /// Get Volume from UsLegalCups. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsLegalCups(double uslegalcups) -#else - public static Volume FromUsLegalCups(QuantityValue uslegalcups) -#endif - { - double value = (double) uslegalcups; - return new Volume(value, VolumeUnit.UsLegalCup); - } - - /// - /// Get Volume from UsOunces. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsOunces(double usounces) -#else - public static Volume FromUsOunces(QuantityValue usounces) -#endif - { - double value = (double) usounces; - return new Volume(value, VolumeUnit.UsOunce); - } - - /// - /// Get Volume from UsPints. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsPints(double uspints) -#else - public static Volume FromUsPints(QuantityValue uspints) -#endif - { - double value = (double) uspints; - return new Volume(value, VolumeUnit.UsPint); - } - - /// - /// Get Volume from UsQuarts. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsQuarts(double usquarts) -#else - public static Volume FromUsQuarts(QuantityValue usquarts) -#endif - { - double value = (double) usquarts; - return new Volume(value, VolumeUnit.UsQuart); - } - - /// - /// Get Volume from UsTablespoons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTablespoons(double ustablespoons) -#else - public static Volume FromUsTablespoons(QuantityValue ustablespoons) -#endif - { - double value = (double) ustablespoons; - return new Volume(value, VolumeUnit.UsTablespoon); - } - - /// - /// Get Volume from UsTeaspoons. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTeaspoons(double usteaspoons) -#else - public static Volume FromUsTeaspoons(QuantityValue usteaspoons) -#endif - { - double value = (double) usteaspoons; - return new Volume(value, VolumeUnit.UsTeaspoon); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Volume unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Volume From(double value, VolumeUnit fromUnit) -#else - public static Volume From(QuantityValue value, VolumeUnit fromUnit) -#endif - { - return new Volume((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is Volume)) throw new ArgumentException("Expected type Volume.", nameof(obj)); - - return CompareTo((Volume)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(Volume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Volume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is Volume)) - return false; - - var objQuantity = (Volume)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another Volume by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(Volume, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(Volume other, Volume maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Volume. - public override int GetHashCode() - { - return new { type = typeof(Volume), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Volume to another Volume with the unit representation . - /// - /// A Volume with the specified unit. - public Volume ToUnit(VolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Volume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeUnit.AuTablespoon: return _value*2e-5; - case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; - case VolumeUnit.CubicCentimeter: return _value/1e6; - case VolumeUnit.CubicDecimeter: return _value/1e3; - case VolumeUnit.CubicFoot: return _value*0.0283168; - case VolumeUnit.CubicInch: return _value*1.6387*1e-5; - case VolumeUnit.CubicKilometer: return _value*1e9; - case VolumeUnit.CubicMeter: return _value; - case VolumeUnit.CubicMicrometer: return _value/1e18; - case VolumeUnit.CubicMile: return _value*4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return _value/1e9; - case VolumeUnit.CubicYard: return _value*0.764554858; - case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; - case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; - case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; - case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; - case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; - case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; - case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; - case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; - case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; - case VolumeUnit.Kiloliter: return (_value/1e3) * 1e3d; - case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; - case VolumeUnit.Liter: return _value/1e3; - case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; - case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; - case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; - case VolumeUnit.MetricCup: return _value*0.00025; - case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; - case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; - case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; - case VolumeUnit.OilBarrel: return _value*0.158987294928; - case VolumeUnit.Tablespoon: return _value*1.478676478125e-5; - case VolumeUnit.Teaspoon: return _value*4.92892159375e-6; - case VolumeUnit.UkTablespoon: return _value*1.5e-5; - case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; - case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; - case VolumeUnit.UsGallon: return _value*0.00378541; - case VolumeUnit.UsLegalCup: return _value*0.00024; - case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return _value*4.73176473e-4; - case VolumeUnit.UsQuart: return _value*9.46352946e-4; - case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeUnit unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; - case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; - case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; - case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; - case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; - case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); - case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; - case VolumeUnit.CubicMeter: return baseUnitValue; - case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; - case VolumeUnit.CubicMile: return baseUnitValue/4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; - case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; - case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; - case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; - case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; - case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; - case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; - case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; - case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; - case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; - case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; - case VolumeUnit.Kiloliter: return (baseUnitValue*1e3) / 1e3d; - case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; - case VolumeUnit.Liter: return baseUnitValue*1e3; - case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; - case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; - case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; - case VolumeUnit.MetricCup: return baseUnitValue/0.00025; - case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; - case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; - case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; - case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; - case VolumeUnit.Tablespoon: return baseUnitValue/1.478676478125e-5; - case VolumeUnit.Teaspoon: return baseUnitValue/4.92892159375e-6; - case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; - case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; - case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; - case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; - case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; - case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return baseUnitValue/4.73176473e-4; - case VolumeUnit.UsQuart: return baseUnitValue/9.46352946e-4; - case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Volume Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Volume result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is CubicMeter - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static VolumeUnit ToStringDefaultUnit { get; set; } = VolumeUnit.CubicMeter; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VolumeUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of Volume - /// - public static Volume MaxValue => new Volume(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of Volume - /// - public static Volume MinValue => new Volume(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => Volume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Volume.BaseDimensions; - } -} diff --git a/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs b/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs deleted file mode 100644 index d585adc5ac..0000000000 --- a/Common/GeneratedCode/Quantities/VolumeFlow.Common.g.cs +++ /dev/null @@ -1,1057 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class VolumeFlow : IQuantity -#else - public partial struct VolumeFlow : IQuantity, IComparable, IComparable -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeFlowUnit? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - static VolumeFlow() - { - BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); - } - - /// - /// Creates the quantity with the given value in the base unit CubicMeterPerSecond. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public VolumeFlow(double cubicmeterspersecond) - { - _value = Convert.ToDouble(cubicmeterspersecond); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - VolumeFlow(double numericValue, VolumeFlowUnit unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. - /// - /// Value assuming base unit CubicMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - VolumeFlow(long cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. - /// - /// Value assuming base unit CubicMeterPerSecond. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - VolumeFlow(decimal cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.VolumeFlow; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the VolumeFlow quantity. - /// - public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); - - /// - /// Get VolumeFlow in CentilitersPerMinute. - /// - public double CentilitersPerMinute => As(VolumeFlowUnit.CentilitersPerMinute); - - /// - /// Get VolumeFlow in CubicDecimetersPerMinute. - /// - public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); - - /// - /// Get VolumeFlow in CubicFeetPerHour. - /// - public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); - - /// - /// Get VolumeFlow in CubicFeetPerMinute. - /// - public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); - - /// - /// Get VolumeFlow in CubicFeetPerSecond. - /// - public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); - - /// - /// Get VolumeFlow in CubicMetersPerHour. - /// - public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); - - /// - /// Get VolumeFlow in CubicMetersPerMinute. - /// - public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); - - /// - /// Get VolumeFlow in CubicMetersPerSecond. - /// - public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); - - /// - /// Get VolumeFlow in CubicMillimetersPerSecond. - /// - public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); - - /// - /// Get VolumeFlow in CubicYardsPerHour. - /// - public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); - - /// - /// Get VolumeFlow in CubicYardsPerMinute. - /// - public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); - - /// - /// Get VolumeFlow in CubicYardsPerSecond. - /// - public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); - - /// - /// Get VolumeFlow in DecilitersPerMinute. - /// - public double DecilitersPerMinute => As(VolumeFlowUnit.DecilitersPerMinute); - - /// - /// Get VolumeFlow in KilolitersPerMinute. - /// - public double KilolitersPerMinute => As(VolumeFlowUnit.KilolitersPerMinute); - - /// - /// Get VolumeFlow in KilousGallonsPerMinute. - /// - public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonsPerMinute); - - /// - /// Get VolumeFlow in LitersPerHour. - /// - public double LitersPerHour => As(VolumeFlowUnit.LitersPerHour); - - /// - /// Get VolumeFlow in LitersPerMinute. - /// - public double LitersPerMinute => As(VolumeFlowUnit.LitersPerMinute); - - /// - /// Get VolumeFlow in LitersPerSecond. - /// - public double LitersPerSecond => As(VolumeFlowUnit.LitersPerSecond); - - /// - /// Get VolumeFlow in MicrolitersPerMinute. - /// - public double MicrolitersPerMinute => As(VolumeFlowUnit.MicrolitersPerMinute); - - /// - /// Get VolumeFlow in MillilitersPerMinute. - /// - public double MillilitersPerMinute => As(VolumeFlowUnit.MillilitersPerMinute); - - /// - /// Get VolumeFlow in MillionUsGallonsPerDay. - /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); - - /// - /// Get VolumeFlow in NanolitersPerMinute. - /// - public double NanolitersPerMinute => As(VolumeFlowUnit.NanolitersPerMinute); - - /// - /// Get VolumeFlow in OilBarrelsPerDay. - /// - public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelsPerDay); - - /// - /// Get VolumeFlow in OilBarrelsPerHour. - /// - public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelsPerHour); - - /// - /// Get VolumeFlow in OilBarrelsPerMinute. - /// - public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelsPerMinute); - - /// - /// Get VolumeFlow in UsGallonsPerHour. - /// - public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonsPerHour); - - /// - /// Get VolumeFlow in UsGallonsPerMinute. - /// - public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonsPerMinute); - - /// - /// Get VolumeFlow in UsGallonsPerSecond. - /// - public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonsPerSecond); - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - public static VolumeFlow Zero => new VolumeFlow(0, BaseUnit); - - /// - /// Get VolumeFlow from CentilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) -#else - public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) -#endif - { - double value = (double) centilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CentilitersPerMinute); - } - - /// - /// Get VolumeFlow from CubicDecimetersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) -#else - public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) -#endif - { - double value = (double) cubicdecimetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); - } - - /// - /// Get VolumeFlow from CubicFeetPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) -#else - public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) -#endif - { - double value = (double) cubicfeetperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); - } - - /// - /// Get VolumeFlow from CubicFeetPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) -#else - public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) -#endif - { - double value = (double) cubicfeetperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); - } - - /// - /// Get VolumeFlow from CubicFeetPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) -#else - public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) -#endif - { - double value = (double) cubicfeetpersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); - } - - /// - /// Get VolumeFlow from CubicMetersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) -#else - public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) -#endif - { - double value = (double) cubicmetersperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); - } - - /// - /// Get VolumeFlow from CubicMetersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) -#else - public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) -#endif - { - double value = (double) cubicmetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); - } - - /// - /// Get VolumeFlow from CubicMetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) -#else - public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) -#endif - { - double value = (double) cubicmeterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); - } - - /// - /// Get VolumeFlow from CubicMillimetersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMillimetersPerSecond(double cubicmillimeterspersecond) -#else - public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue cubicmillimeterspersecond) -#endif - { - double value = (double) cubicmillimeterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); - } - - /// - /// Get VolumeFlow from CubicYardsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) -#else - public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) -#endif - { - double value = (double) cubicyardsperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); - } - - /// - /// Get VolumeFlow from CubicYardsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) -#else - public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) -#endif - { - double value = (double) cubicyardsperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); - } - - /// - /// Get VolumeFlow from CubicYardsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) -#else - public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) -#endif - { - double value = (double) cubicyardspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); - } - - /// - /// Get VolumeFlow from DecilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) -#else - public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) -#endif - { - double value = (double) decilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.DecilitersPerMinute); - } - - /// - /// Get VolumeFlow from KilolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) -#else - public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) -#endif - { - double value = (double) kilolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.KilolitersPerMinute); - } - - /// - /// Get VolumeFlow from KilousGallonsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilousGallonsPerMinute(double kilousgallonsperminute) -#else - public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue kilousgallonsperminute) -#endif - { - double value = (double) kilousgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.KilousGallonsPerMinute); - } - - /// - /// Get VolumeFlow from LitersPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerHour(double litersperhour) -#else - public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) -#endif - { - double value = (double) litersperhour; - return new VolumeFlow(value, VolumeFlowUnit.LitersPerHour); - } - - /// - /// Get VolumeFlow from LitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerMinute(double litersperminute) -#else - public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) -#endif - { - double value = (double) litersperminute; - return new VolumeFlow(value, VolumeFlowUnit.LitersPerMinute); - } - - /// - /// Get VolumeFlow from LitersPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerSecond(double literspersecond) -#else - public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) -#endif - { - double value = (double) literspersecond; - return new VolumeFlow(value, VolumeFlowUnit.LitersPerSecond); - } - - /// - /// Get VolumeFlow from MicrolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) -#else - public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) -#endif - { - double value = (double) microlitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MicrolitersPerMinute); - } - - /// - /// Get VolumeFlow from MillilitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) -#else - public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) -#endif - { - double value = (double) millilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MillilitersPerMinute); - } - - /// - /// Get VolumeFlow from MillionUsGallonsPerDay. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) -#else - public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) -#endif - { - double value = (double) millionusgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); - } - - /// - /// Get VolumeFlow from NanolitersPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) -#else - public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) -#endif - { - double value = (double) nanolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.NanolitersPerMinute); - } - - /// - /// Get VolumeFlow from OilBarrelsPerDay. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) -#else - public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) -#endif - { - double value = (double) oilbarrelsperday; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelsPerDay); - } - - /// - /// Get VolumeFlow from OilBarrelsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerHour(double oilbarrelsperhour) -#else - public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) -#endif - { - double value = (double) oilbarrelsperhour; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelsPerHour); - } - - /// - /// Get VolumeFlow from OilBarrelsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerMinute(double oilbarrelsperminute) -#else - public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) -#endif - { - double value = (double) oilbarrelsperminute; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelsPerMinute); - } - - /// - /// Get VolumeFlow from UsGallonsPerHour. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) -#else - public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) -#endif - { - double value = (double) usgallonsperhour; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerHour); - } - - /// - /// Get VolumeFlow from UsGallonsPerMinute. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) -#else - public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) -#endif - { - double value = (double) usgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerMinute); - } - - /// - /// Get VolumeFlow from UsGallonsPerSecond. - /// -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) -#else - public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) -#endif - { - double value = (double) usgallonspersecond; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerSecond); - } - - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumeFlow unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) -#else - public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) -#endif - { - return new VolumeFlow((double)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is VolumeFlow)) throw new ArgumentException("Expected type VolumeFlow.", nameof(obj)); - - return CompareTo((VolumeFlow)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo(VolumeFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VolumeFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public override bool Equals(object obj) - { - if(obj is null || !(obj is VolumeFlow)) - return false; - - var objQuantity = (VolumeFlow)obj; - return _value.Equals(objQuantity.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); - } - - /// - /// Compare equality to another VolumeFlow by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals(VolumeFlow, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals(VolumeFlow other, VolumeFlow maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlow. - public override int GetHashCode() - { - return new { type = typeof(VolumeFlow), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumeFlow to another VolumeFlow with the unit representation . - /// - /// A VolumeFlow with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumeFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeFlowUnit.CentilitersPerMinute: return (_value/60000.00000) * 1e-2d; - case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; - case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; - case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; - case VolumeFlowUnit.CubicMeterPerSecond: return _value; - case VolumeFlowUnit.CubicMillimeterPerSecond: return _value*1e-9; - case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; - case VolumeFlowUnit.DecilitersPerMinute: return (_value/60000.00000) * 1e-1d; - case VolumeFlowUnit.KilolitersPerMinute: return (_value/60000.00000) * 1e3d; - case VolumeFlowUnit.KilousGallonsPerMinute: return _value/15.850323141489; - case VolumeFlowUnit.LitersPerHour: return _value/3600000.000; - case VolumeFlowUnit.LitersPerMinute: return _value/60000.00000; - case VolumeFlowUnit.LitersPerSecond: return _value/1000; - case VolumeFlowUnit.MicrolitersPerMinute: return (_value/60000.00000) * 1e-6d; - case VolumeFlowUnit.MillilitersPerMinute: return (_value/60000.00000) * 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; - case VolumeFlowUnit.NanolitersPerMinute: return (_value/60000.00000) * 1e-9d; - case VolumeFlowUnit.OilBarrelsPerDay: return _value*1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelsPerHour: return _value*4.41631375e-5; - case VolumeFlowUnit.OilBarrelsPerMinute: return _value*2.64978825e-3; - case VolumeFlowUnit.UsGallonsPerHour: return _value/951019.38848933424; - case VolumeFlowUnit.UsGallonsPerMinute: return _value/15850.323141489; - case VolumeFlowUnit.UsGallonsPerSecond: 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.CentilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; - case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; - case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; - case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; - case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; - case VolumeFlowUnit.CubicMillimeterPerSecond: return baseUnitValue/1e-9; - case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; - case VolumeFlowUnit.DecilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; - case VolumeFlowUnit.KilolitersPerMinute: return (baseUnitValue*60000.00000) / 1e3d; - case VolumeFlowUnit.KilousGallonsPerMinute: return baseUnitValue*15.850323141489; - case VolumeFlowUnit.LitersPerHour: return baseUnitValue*3600000.000; - case VolumeFlowUnit.LitersPerMinute: return baseUnitValue*60000.00000; - case VolumeFlowUnit.LitersPerSecond: return baseUnitValue*1000; - case VolumeFlowUnit.MicrolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; - case VolumeFlowUnit.MillilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; - case VolumeFlowUnit.NanolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; - case VolumeFlowUnit.OilBarrelsPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelsPerHour: return baseUnitValue/4.41631375e-5; - case VolumeFlowUnit.OilBarrelsPerMinute: return baseUnitValue/2.64978825e-3; - case VolumeFlowUnit.UsGallonsPerHour: return baseUnitValue*951019.38848933424; - case VolumeFlowUnit.UsGallonsPerMinute: return baseUnitValue*15850.323141489; - case VolumeFlowUnit.UsGallonsPerSecond: return baseUnitValue*264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumeFlow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumeFlow result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeFlowUnit ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is CubicMeterPerSecond - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static VolumeFlowUnit ToStringDefaultUnit { get; set; } = VolumeFlowUnit.CubicMeterPerSecond; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString(VolumeFlowUnit unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of VolumeFlow - /// - public static VolumeFlow MaxValue => new VolumeFlow(double.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of VolumeFlow - /// - public static VolumeFlow MinValue => new VolumeFlow(double.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => VolumeFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; - } -} diff --git a/Common/UnitDefinitions/Duration.json b/Common/UnitDefinitions/Duration.json index ad19f0f063..7343405e0e 100644 --- a/Common/UnitDefinitions/Duration.json +++ b/Common/UnitDefinitions/Duration.json @@ -6,23 +6,6 @@ "T": 1 }, "Units": [ - { - "ObsoleteText": "Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.", - "SingularName": "Year", - "PluralName": "Years", - "FromUnitToBaseFunc": "x*365*24*3600", - "FromBaseToUnitFunc": "x/(365*24*3600)", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "yr", "year", "years" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "год" ] - } - ] - }, { "SingularName": "Year365", "PluralName": "Years365", @@ -39,23 +22,6 @@ } ] }, - { - "ObsoleteText": "Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.", - "SingularName": "Month", - "PluralName": "Months", - "FromUnitToBaseFunc": "x*30*24*3600", - "FromBaseToUnitFunc": "x/(30*24*3600)", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "mo", "month", "months" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "месяц" ] - } - ] - }, { "SingularName": "Month30", "PluralName": "Months30", diff --git a/Common/UnitDefinitions/Flow.json b/Common/UnitDefinitions/Flow.json deleted file mode 100644 index 2b4918d122..0000000000 --- a/Common/UnitDefinitions/Flow.json +++ /dev/null @@ -1,263 +0,0 @@ -{ - "Name": "Flow", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "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.", - "BaseDimensions": { - "L": 3, - "T": -1 - }, - "Units": [ - { - "SingularName": "CubicMeterPerSecond", - "PluralName": "CubicMetersPerSecond", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x", - "FromBaseToUnitFunc": "x", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "m³/s" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "м³/с" ] - } - ] - }, - { - "SingularName": "CubicMeterPerMinute", - "PluralName": "CubicMetersPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/60", - "FromBaseToUnitFunc": "x*60", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "m³/min" ] - } - ] - }, - { - "SingularName": "CubicMeterPerHour", - "PluralName": "CubicMetersPerHour", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/3600", - "FromBaseToUnitFunc": "x*3600", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "m³/h" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "м³/ч" ] - } - ] - }, - { - "SingularName": "CubicFootPerSecond", - "PluralName": "CubicFeetPerSecond", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/35.314666721", - "FromBaseToUnitFunc": "x*35.314666721", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "ft³/s" ] - } - ] - }, - { - "SingularName": "CubicFootPerMinute", - "PluralName": "CubicFeetPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/2118.88000326", - "FromBaseToUnitFunc": "x*2118.88000326", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "ft³/min" ] - } - ] - }, - { - "SingularName": "CubicFootPerHour", - "PluralName": "CubicFeetPerHour", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x*7.8657907199999087346816086183876e-6", - "FromBaseToUnitFunc": "x/7.8657907199999087346816086183876e-6", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "ft³/h", "cf/hr" ] - } - ] - }, - { - "SingularName": "CubicYardPerSecond", - "PluralName": "CubicYardsPerSecond", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x*0.764554857984", - "FromBaseToUnitFunc": "x/0.764554857984", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "yd³/s" ] - } - ] - }, - { - "SingularName": "CubicYardPerMinute", - "PluralName": "CubicYardsPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x*0.0127425809664", - "FromBaseToUnitFunc": "x/0.0127425809664", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "yd³/min" ] - } - ] - }, - { - "SingularName": "CubicYardPerHour", - "PluralName": "CubicYardsPerHour", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x*2.1237634944E-4", - "FromBaseToUnitFunc": "x/2.1237634944E-4", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "yd³/h" ] - } - ] - }, - { - "SingularName": "MillionUsGallonsPerDay", - "PluralName": "MillionUsGallonsPerDay", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/22.824465227", - "FromBaseToUnitFunc": "x*22.824465227", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "MGD" ] - } - ] - }, - { - "SingularName": "LitersPerSecond", - "PluralName": "LitersPerSecond", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/1000", - "FromBaseToUnitFunc": "x*1000", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "LPS" ] - } - ] - }, - { - "SingularName": "LitersPerMinute", - "PluralName": "LitersPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/60000.00000", - "FromBaseToUnitFunc": "x*60000.00000", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "LPM" ] - } - ] - }, - { - "SingularName": "LitersPerHour", - "PluralName": "LitersPerHour", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/3600000.000", - "FromBaseToUnitFunc": "x*3600000.000", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "LPH" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "л/ч" ] - } - ] - }, - { - "SingularName": "UsGallonsPerSecond", - "PluralName": "UsGallonsPerSecond", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/264.1720523581484", - "FromBaseToUnitFunc": "x*264.1720523581484", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/s" ] - } - ] - }, - { - "SingularName": "UsGallonsPerMinute", - "PluralName": "UsGallonsPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/15850.323141489", - "FromBaseToUnitFunc": "x*15850.323141489", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/min", "GPM" ] - } - ] - }, - { - "SingularName": "UsGallonsPerHour", - "PluralName": "UsGallonsPerHour", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/951019.38848933424", - "FromBaseToUnitFunc": "x*951019.38848933424", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/h" ] - } - ] - }, - { - "SingularName": "CubicDecimeterPerMinute", - "PluralName": "CubicDecimetersPerMinute", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x/60000.00000", - "FromBaseToUnitFunc": "x*60000.00000", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "dm³/min" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "дм³/мин" ] - } - ] - }, - { - "SingularName": "OilBarrelsPerDay", - "PluralName": "OilBarrelsPerDay", - "ObsoleteText": "Deprecated due to github issue #363, please use VolumeFlow instead", - "FromUnitToBaseFunc": "x*1.8401307283333333333333333333333e-6", - "FromBaseToUnitFunc": "x/1.8401307283333333333333333333333e-6", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "bbl/d", "BOPD" ] - } - ] - } - ] -} diff --git a/Common/UnitDefinitions/Length.json b/Common/UnitDefinitions/Length.json index 2ee0fd3767..ea24e97c88 100644 --- a/Common/UnitDefinitions/Length.json +++ b/Common/UnitDefinitions/Length.json @@ -64,7 +64,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft", "'" ] + "Abbreviations": [ "ft", "'", "′" ] }, { "Culture": "ru-RU", @@ -92,7 +92,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in", "\\\"" ] + "Abbreviations": [ "in", "\\\"", "″" ] }, { "Culture": "ru-RU", @@ -233,4 +233,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Pressure.json b/Common/UnitDefinitions/Pressure.json index 21d85ae4b6..f1daa4f6f3 100644 --- a/Common/UnitDefinitions/Pressure.json +++ b/Common/UnitDefinitions/Pressure.json @@ -161,23 +161,6 @@ } ] }, - { - "SingularName": "Psi", - "PluralName": "Psi", - "ObsoleteText": "Deprecated due to github issue #215, please use PoundForcePerSquareInch instead", - "FromUnitToBaseFunc": "x*6.894757293168361e3", - "FromBaseToUnitFunc": "x/6.894757293168361e3", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "psi" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "psi" ] - } - ] - }, { "SingularName": "TechnicalAtmosphere", "PluralName": "TechnicalAtmospheres", diff --git a/Common/UnitDefinitions/TemperatureDelta.json b/Common/UnitDefinitions/TemperatureDelta.json index 771f916667..34b37da1ea 100644 --- a/Common/UnitDefinitions/TemperatureDelta.json +++ b/Common/UnitDefinitions/TemperatureDelta.json @@ -98,110 +98,6 @@ "Abbreviations": [ "∆°Rø" ] } ] - }, - { - "SingularName": "KelvinDelta", - "PluralName": "KelvinsDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use Kelvin instead", - "FromUnitToBaseFunc": "x", - "FromBaseToUnitFunc": "x", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆K" ] - } - ] - }, - { - "SingularName": "DegreeCelsiusDelta", - "PluralName": "DegreesCelsiusDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeCelsius instead", - "FromUnitToBaseFunc": "x", - "FromBaseToUnitFunc": "x", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°C" ] - } - ] - }, - { - "SingularName": "DegreeDelisleDelta", - "PluralName": "DegreesDelisleDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeDelisle instead", - "FromUnitToBaseFunc": "x*-2/3", - "FromBaseToUnitFunc": "x*-3/2", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°De" ] - } - ] - }, - { - "SingularName": "DegreeFahrenheitDelta", - "PluralName": "DegreesFahrenheitDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeFahrenheit instead", - "FromUnitToBaseFunc": "x*5/9", - "FromBaseToUnitFunc": "x*9/5", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°F" ] - } - ] - }, - { - "SingularName": "DegreeNewtonDelta", - "PluralName": "DegreesNewtonDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeNewton instead", - "FromUnitToBaseFunc": "x*100/33", - "FromBaseToUnitFunc": "x*33/100", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°N" ] - } - ] - }, - { - "SingularName": "DegreeRankineDelta", - "PluralName": "DegreesRankineDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeRankine instead", - "FromUnitToBaseFunc": "x*5/9", - "FromBaseToUnitFunc": "x*9/5", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°R" ] - } - ] - }, - { - "SingularName": "DegreeReaumurDelta", - "PluralName": "DegreesReaumurDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeReaumur instead", - "FromUnitToBaseFunc": "x*5/4", - "FromBaseToUnitFunc": "x*4/5", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°Ré" ] - } - ] - }, - { - "SingularName": "DegreeRoemerDelta", - "PluralName": "DegreesRoemerDelta", - "ObsoleteText": "Deprecated due to github issue #180, please use DegreeRoemer instead", - "FromUnitToBaseFunc": "x*40/21", - "FromBaseToUnitFunc": "x*21/40", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "∆°Rø" ] - } - ] } ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/Volume.json b/Common/UnitDefinitions/Volume.json index abb64bc7ce..4eef10b912 100644 --- a/Common/UnitDefinitions/Volume.json +++ b/Common/UnitDefinitions/Volume.json @@ -252,48 +252,6 @@ } ] }, - { - "SingularName": "Tablespoon", - "PluralName": "Tablespoons", - "ObsoleteText": "Deprecated due to github issue #134, please use UsTablespoon instead", - "FromUnitToBaseFunc": "x*1.478676478125e-5", - "FromBaseToUnitFunc": "x/1.478676478125e-5", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "Tbsp", "Tbs", "T", "tb", "tbs", "tbsp", "tblsp", "tblspn", "Tbsp.", "Tbs.", "T.", "tb.", "tbs.", "tbsp.", "tblsp.", "tblspn.", "tablespoon", "Tablespoon" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "столовая ложка" ] - }, - { - "Culture": "nb-NO", - "Abbreviations": [ "ss", "ss.", "SS", "SS." ] - } - ] - }, - { - "SingularName": "Teaspoon", - "PluralName": "Teaspoons", - "ObsoleteText": "Deprecated due to github issue #134, please use UsTeaspoon instead", - "FromUnitToBaseFunc": "x*4.92892159375e-6", - "FromBaseToUnitFunc": "x/4.92892159375e-6", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon" ] - }, - { - "Culture": "ru-RU", - "Abbreviations": [ "чайная ложка" ] - }, - { - "Culture": "nb-NO", - "Abbreviations": [ "ts", "ts." ] - } - ] - }, { "SingularName": "UsTablespoon", "PluralName": "UsTablespoons", diff --git a/Common/UnitDefinitions/VolumeFlow.json b/Common/UnitDefinitions/VolumeFlow.json index d0440363e1..cec7dec73a 100644 --- a/Common/UnitDefinitions/VolumeFlow.json +++ b/Common/UnitDefinitions/VolumeFlow.json @@ -1,4 +1,4 @@ -{ +{ "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.", @@ -136,7 +136,7 @@ ] }, { - "SingularName": "LitersPerSecond", + "SingularName": "LiterPerSecond", "PluralName": "LitersPerSecond", "FromUnitToBaseFunc": "x/1000", "FromBaseToUnitFunc": "x*1000", @@ -148,7 +148,7 @@ ] }, { - "SingularName": "LitersPerMinute", + "SingularName": "LiterPerMinute", "PluralName": "LitersPerMinute", "FromUnitToBaseFunc": "x/60000.00000", "FromBaseToUnitFunc": "x*60000.00000", @@ -161,7 +161,7 @@ ] }, { - "SingularName": "LitersPerHour", + "SingularName": "LiterPerHour", "PluralName": "LitersPerHour", "FromUnitToBaseFunc": "x/3600000.000", "FromBaseToUnitFunc": "x*3600000.000", @@ -177,7 +177,7 @@ ] }, { - "SingularName": "UsGallonsPerSecond", + "SingularName": "UsGallonPerSecond", "PluralName": "UsGallonsPerSecond", "FromUnitToBaseFunc": "x/264.1720523581484", "FromBaseToUnitFunc": "x*264.1720523581484", @@ -189,7 +189,7 @@ ] }, { - "SingularName": "UsGallonsPerMinute", + "SingularName": "UsGallonPerMinute", "PluralName": "UsGallonsPerMinute", "FromUnitToBaseFunc": "x/15850.323141489", "FromBaseToUnitFunc": "x*15850.323141489", @@ -213,7 +213,7 @@ ] }, { - "SingularName": "UsGallonsPerHour", + "SingularName": "UsGallonPerHour", "PluralName": "UsGallonsPerHour", "FromUnitToBaseFunc": "x/951019.38848933424", "FromBaseToUnitFunc": "x*951019.38848933424", @@ -241,7 +241,7 @@ ] }, { - "SingularName": "OilBarrelsPerDay", + "SingularName": "OilBarrelPerDay", "PluralName": "OilBarrelsPerDay", "FromUnitToBaseFunc": "x*1.8401307283333333333333333333333e-6", "FromBaseToUnitFunc": "x/1.8401307283333333333333333333333e-6", @@ -253,7 +253,7 @@ ] }, { - "SingularName": "OilBarrelsPerMinute", + "SingularName": "OilBarrelPerMinute", "PluralName": "OilBarrelsPerMinute", "FromUnitToBaseFunc": "x*2.64978825e-3", "FromBaseToUnitFunc": "x/2.64978825e-3", @@ -265,7 +265,7 @@ ] }, { - "SingularName": "OilBarrelsPerHour", + "SingularName": "OilBarrelPerHour", "PluralName": "OilBarrelsPerHour", "FromUnitToBaseFunc": "x*4.41631375e-5", "FromBaseToUnitFunc": "x/4.41631375e-5", diff --git a/README.md b/README.md index 0fdc875ee0..ce30d82c7e 100644 --- a/README.md +++ b/README.md @@ -11,20 +11,18 @@ Stop littering your code with unnecessary calculations, Units.NET gives you all ### Build Targets -* .NET Standard 1.0 +* .NET Standard 2.0 * .NET 4.0 -* .NET 3.5 Client * [Windows Runtime Component](https://docs.microsoft.com/en-us/windows/uwp/winrt-components/) for UWP apps (JavaScript, C++ or C#) ### Overview -* [50+ quantities with a total of 600+ units](UnitsNet/GeneratedCode/Units) generated from [JSON](Common/UnitDefinitions/) by [Powershell scripts](UnitsNet/Scripts) -* [1000+ unit tests](https://ci.appveyor.com/project/angularsen/unitsnet) on conversions and localizations +* [89 quantities with over 750 units](UnitsNet/GeneratedCode/Units) generated from [JSON](Common/UnitDefinitions/) by [Powershell scripts](UnitsNet/Scripts) +* [1900+ unit tests](https://ci.appveyor.com/project/angularsen/unitsnet) on conversions and localizations * Immutable structs that implement `Equatable`, `IComparable` * [Static typing](#static-typing) to avoid ambiguous values or units * [Operator overloads](#operator-overloads) for arithmetic on quantities -* [Extension methods](#extension-methods) for short-hand creation and conversions * [Parse and ToString()](#culture) supports cultures and localization * [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) @@ -76,21 +74,6 @@ Acceleration a2 = Force.FromNewtons(100) / Mass.FromKilograms(20); RotationalSpeed r = Angle.FromDegrees(90) / TimeSpan.FromSeconds(2); ``` -### Extension Methods - -All units have associated extension methods for a really compact, expressive way to construct values or do arithmetic. -```C# -using UnitsNet.Extensions.NumberToDuration; -using UnitsNet.Extensions.NumberToLength; -using UnitsNet.Extensions.NumberToTimeSpan; - -Speed speed = 30.Kilometers() / 1.Hours(); // 30 km/h (using Duration type) -Length distance = speed * 2.h(); // 60 km (using TimeSpan type) - -Acceleration stdGravity = 9.80665.MetersPerSecondSquared(); -Force weight = 80.Kilograms() * stdGravity; // 80 kilograms-force or 784.532 newtons -``` - ### 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: @@ -133,7 +116,7 @@ Example: ### Example: Creating a dynamic 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-02-04) (release 2018-02-04 for Windows) +[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) diff --git a/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj b/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj index 64da47640d..593b33c624 100644 --- a/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj +++ b/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj @@ -1,19 +1,17 @@ - + - netcoreapp1.0 - ConsoleApp-NetCore + netcoreapp2.1 Exe - ConsoleApp-NetCore - 1.0.4 - $(PackageTargetFallback);dnxcore50 - false - false - false + ConsoleApp1.Program - + + + + + diff --git a/Samples/ConsoleApp-NetCore/Program.cs b/Samples/ConsoleApp-NetCore/Program.cs index 60b6e928b5..4d4141d683 100644 --- a/Samples/ConsoleApp-NetCore/Program.cs +++ b/Samples/ConsoleApp-NetCore/Program.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using UnitsNet; namespace ConsoleApp1 diff --git a/Samples/ConsoleApp-NetCore/Properties/AssemblyInfo.cs b/Samples/ConsoleApp-NetCore/Properties/AssemblyInfo.cs deleted file mode 100644 index 535ecf599f..0000000000 --- a/Samples/ConsoleApp-NetCore/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +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: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ConsoleApp1")] -[assembly: AssemblyTrademark("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("955a6cbf-c4e3-4c55-85c8-613e2ca4ccd7")] diff --git a/Samples/Samples.sln b/Samples/Samples.sln index 0d8fc0f162..e125d7998a 100644 --- a/Samples/Samples.sln +++ b/Samples/Samples.sln @@ -9,24 +9,104 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitConverter.Wpf", "UnitCo 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}" +EndProject +Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "SimpleConversionDemo.UWP.WinJS", "SimpleConversionDemo.UWP.WinJS\SimpleConversionDemo.UWP.WinJS.jsproj", "{F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}" +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 {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 + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|x64.ActiveCfg = Debug|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|x64.Build.0 = Debug|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|x86.ActiveCfg = Debug|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|x86.Build.0 = Debug|Any CPU {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|Any CPU.ActiveCfg = Release|Any CPU {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|Any CPU.Build.0 = Release|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|ARM.ActiveCfg = Release|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|x64.ActiveCfg = Release|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|x64.Build.0 = Release|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|x86.ActiveCfg = Release|Any CPU + {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Release|x86.Build.0 = Release|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|ARM.ActiveCfg = Debug|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|x64.ActiveCfg = Debug|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|x64.Build.0 = Debug|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|x86.ActiveCfg = Debug|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Debug|x86.Build.0 = Debug|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|Any CPU.ActiveCfg = Release|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|Any CPU.Build.0 = Release|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|ARM.ActiveCfg = Release|Any CPU + {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|x64.ActiveCfg = Release|Any CPU + {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 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/UnitsNet.TestApps.Uwp.Csharp/.gitignore b/Samples/SimpleConversionDemo.UWP.CSharp/.gitignore similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/.gitignore rename to Samples/SimpleConversionDemo.UWP.CSharp/.gitignore diff --git a/UnitsNet.TestApps.Uwp.Csharp/App.xaml b/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/App.xaml rename to Samples/SimpleConversionDemo.UWP.CSharp/App.xaml diff --git a/UnitsNet.TestApps.Uwp.Csharp/App.xaml.cs b/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml.cs similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/App.xaml.cs rename to Samples/SimpleConversionDemo.UWP.CSharp/App.xaml.cs diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/LockScreenLogo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/LockScreenLogo.scale-200.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/LockScreenLogo.scale-200.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/LockScreenLogo.scale-200.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/SplashScreen.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/SplashScreen.scale-200.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/SplashScreen.scale-200.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/SplashScreen.scale-200.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/Square150x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square150x150Logo.scale-200.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/Square150x150Logo.scale-200.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square150x150Logo.scale-200.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/Square44x44Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.scale-200.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/Square44x44Logo.scale-200.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.scale-200.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/StoreLogo.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/StoreLogo.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/StoreLogo.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/StoreLogo.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/Assets/Wide310x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Wide310x150Logo.scale-200.png similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Assets/Wide310x150Logo.scale-200.png rename to Samples/SimpleConversionDemo.UWP.CSharp/Assets/Wide310x150Logo.scale-200.png diff --git a/UnitsNet.TestApps.Uwp.Csharp/MainPage.xaml b/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/MainPage.xaml rename to Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml diff --git a/UnitsNet.TestApps.Uwp.Csharp/MainPage.xaml.cs b/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs similarity index 78% rename from UnitsNet.TestApps.Uwp.Csharp/MainPage.xaml.cs rename to Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs index 7905f7df5f..d2e8c25c54 100644 --- a/UnitsNet.TestApps.Uwp.Csharp/MainPage.xaml.cs +++ b/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs @@ -19,9 +19,9 @@ public MainPage() InitializeComponent(); // Test some variations, From() constructors, Parse(), As() - string celsius = Temperature.FromDegreesCelsius(100).ToString(TemperatureUnit.DegreeCelsius); - string fahrenheit = Temperature.Parse("100 °C").ToString(TemperatureUnit.DegreeFahrenheit); - string kelvin = Temperature.FromDegreesCelsius(Temperature.Parse(fahrenheit).As(TemperatureUnit.DegreeCelsius)).ToString(TemperatureUnit.Kelvin); + 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) diff --git a/UnitsNet.TestApps.Uwp.Csharp/Package.appxmanifest b/Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest similarity index 95% rename from UnitsNet.TestApps.Uwp.Csharp/Package.appxmanifest rename to Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest index 23c4bac2b3..4aa128459b 100644 --- a/UnitsNet.TestApps.Uwp.Csharp/Package.appxmanifest +++ b/Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest @@ -1,6 +1,6 @@  - + UWP diff --git a/UnitsNet.TestApps.Uwp.Csharp/Properties/AssemblyInfo.cs b/Samples/SimpleConversionDemo.UWP.CSharp/Properties/AssemblyInfo.cs similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Properties/AssemblyInfo.cs rename to Samples/SimpleConversionDemo.UWP.CSharp/Properties/AssemblyInfo.cs diff --git a/UnitsNet.TestApps.Uwp.Csharp/Properties/Default.rd.xml b/Samples/SimpleConversionDemo.UWP.CSharp/Properties/Default.rd.xml similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/Properties/Default.rd.xml rename to Samples/SimpleConversionDemo.UWP.CSharp/Properties/Default.rd.xml diff --git a/UnitsNet.TestApps.Uwp.Csharp/README.md b/Samples/SimpleConversionDemo.UWP.CSharp/README.md similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/README.md rename to Samples/SimpleConversionDemo.UWP.CSharp/README.md diff --git a/UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp.csproj b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj similarity index 94% rename from UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp.csproj rename to Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj index d89fc5a964..19f9c3b450 100644 --- a/UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp.csproj +++ b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj @@ -12,12 +12,12 @@ en-US UAP 10.0.16299.0 - 10.0.10240.0 + 10.0.16299.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - UnitsNet.TestApps.Uwp.Csharp_TemporaryKey.pfx - A1E3AD6087EF223EE6E43EE09818599CAE918FEE + SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx + E98156EA0B8126C89A2653E1CBF645701A704E52 true @@ -91,7 +91,7 @@ - + diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx new file mode 100644 index 0000000000..61cfb8eca2 Binary files /dev/null and b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx differ diff --git a/UnitsNet.TestApps.Uwp.Csharp/build.bat b/Samples/SimpleConversionDemo.UWP.CSharp/build.bat similarity index 100% rename from UnitsNet.TestApps.Uwp.Csharp/build.bat rename to Samples/SimpleConversionDemo.UWP.CSharp/build.bat diff --git a/UnitsNet.TestApps.Uwp.WinJS/project.json b/Samples/SimpleConversionDemo.UWP.CSharp/project.json similarity index 60% rename from UnitsNet.TestApps.Uwp.WinJS/project.json rename to Samples/SimpleConversionDemo.UWP.CSharp/project.json index a216036b9c..c0ecdfc923 100644 --- a/UnitsNet.TestApps.Uwp.WinJS/project.json +++ b/Samples/SimpleConversionDemo.UWP.CSharp/project.json @@ -1,10 +1,10 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "6.0.6", - "UnitsNet.WindowsRuntimeComponent": "3.64.0" + "Microsoft.NETCore.UniversalWindowsPlatform": "6.1.9", + "UnitsNet.WindowsRuntimeComponent": "4.0.0-beta1" }, "frameworks": { - "uap10.0": {} + "uap10.0.16299": {} }, "runtimes": { "win10-arm": {}, diff --git a/UnitsNet.TestApps.Uwp.WinJS/README.md b/Samples/SimpleConversionDemo.UWP.WinJS/README.md similarity index 100% rename from UnitsNet.TestApps.Uwp.WinJS/README.md rename to Samples/SimpleConversionDemo.UWP.WinJS/README.md diff --git a/UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS.jsproj b/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj similarity index 90% rename from UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS.jsproj rename to Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj index 866b991d93..4b820238c5 100644 --- a/UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS.jsproj +++ b/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj @@ -52,7 +52,8 @@ 10.0.16299.0 $(VersionNumberMajor).$(VersionNumberMinor) en-US - UnitsNet.TestApps.Uwp.WinJS_TemporaryKey.pfx + SimpleConversionDemo.UWP.WinJS_TemporaryKey.pfx + 233FD264CDB1D145E2BAA90728A41382699F2046 @@ -74,15 +75,7 @@ - - - - - ..\packages\UnitsNet.WindowsRuntimeComponent.3.64.0\lib\uap10.0\UnitsNet.winmd - true - True - False - + - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Tools/NUnit/nunit-agent.exe b/Tools/NUnit/nunit-agent.exe deleted file mode 100644 index 637b2562be..0000000000 Binary files a/Tools/NUnit/nunit-agent.exe and /dev/null differ diff --git a/Tools/NUnit/nunit-agent.exe.config b/Tools/NUnit/nunit-agent.exe.config deleted file mode 100644 index de2caf60fd..0000000000 --- a/Tools/NUnit/nunit-agent.exe.config +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Tools/NUnit/nunit-console-x86.exe b/Tools/NUnit/nunit-console-x86.exe deleted file mode 100644 index 672a80ee51..0000000000 Binary files a/Tools/NUnit/nunit-console-x86.exe and /dev/null differ diff --git a/Tools/NUnit/nunit-console-x86.exe.config b/Tools/NUnit/nunit-console-x86.exe.config deleted file mode 100644 index 81e5346c83..0000000000 --- a/Tools/NUnit/nunit-console-x86.exe.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/Tools/NUnit/nunit-console.exe b/Tools/NUnit/nunit-console.exe deleted file mode 100644 index 28734cb44c..0000000000 Binary files a/Tools/NUnit/nunit-console.exe and /dev/null differ diff --git a/Tools/NUnit/nunit-console.exe.config b/Tools/NUnit/nunit-console.exe.config deleted file mode 100644 index 81e5346c83..0000000000 --- a/Tools/NUnit/nunit-console.exe.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/Tools/NUnit/nunit-x86.exe b/Tools/NUnit/nunit-x86.exe deleted file mode 100644 index 9c8147f7a8..0000000000 Binary files a/Tools/NUnit/nunit-x86.exe and /dev/null differ diff --git a/Tools/NUnit/nunit-x86.exe.config b/Tools/NUnit/nunit-x86.exe.config deleted file mode 100644 index 9301f94653..0000000000 --- a/Tools/NUnit/nunit-x86.exe.config +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/Tools/NUnit/nunit.exe b/Tools/NUnit/nunit.exe deleted file mode 100644 index 6d24caf6e9..0000000000 Binary files a/Tools/NUnit/nunit.exe and /dev/null differ diff --git a/Tools/NUnit/nunit.exe.config b/Tools/NUnit/nunit.exe.config deleted file mode 100644 index 9301f94653..0000000000 --- a/Tools/NUnit/nunit.exe.config +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/UnitsNet.AllTargets.sln b/UnitsNet.AllTargets.sln deleted file mode 100644 index 17dd988da7..0000000000 --- a/UnitsNet.AllTargets.sln +++ /dev/null @@ -1,151 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2027 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.NetStandard10", "UnitsNet\UnitsNet.NetStandard10.csproj", "{CBEAD842-07BC-4B08-9D9D-D6659813776F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet", "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj", "{FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.Signed", "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.Signed.csproj", "{7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.NetStandard10.Signed", "UnitsNet\UnitsNet.NetStandard10.Signed.csproj", "{21C1AFDC-354E-4D97-947B-2DB63C529E6E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.Tests", "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj", "{FFEEDF44-F32D-4D92-A75E-487CB0582EB1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Tests", "UnitsNet.Tests\UnitsNet.Tests.csproj", "{0E3B7567-5DF2-44BD-88DB-CCF050D3F943}" -EndProject -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 - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|ARM.ActiveCfg = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|ARM.Build.0 = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|x64.ActiveCfg = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|x64.Build.0 = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|x86.ActiveCfg = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Debug|x86.Build.0 = Debug|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|Any CPU.Build.0 = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|ARM.ActiveCfg = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|ARM.Build.0 = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|x64.ActiveCfg = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|x64.Build.0 = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|x86.ActiveCfg = Release|Any CPU - {CBEAD842-07BC-4B08-9D9D-D6659813776F}.Release|x86.Build.0 = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|ARM.ActiveCfg = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|ARM.Build.0 = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|x64.ActiveCfg = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|x64.Build.0 = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|x86.ActiveCfg = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|x86.Build.0 = Debug|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|Any CPU.Build.0 = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|ARM.ActiveCfg = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|ARM.Build.0 = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|x64.ActiveCfg = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|x64.Build.0 = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|x86.ActiveCfg = Release|Any CPU - {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|x86.Build.0 = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|ARM.ActiveCfg = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|ARM.Build.0 = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|x64.ActiveCfg = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|x64.Build.0 = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|x86.ActiveCfg = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|x86.Build.0 = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|Any CPU.Build.0 = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|ARM.ActiveCfg = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|ARM.Build.0 = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|x64.ActiveCfg = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|x64.Build.0 = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|x86.ActiveCfg = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|x86.Build.0 = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|ARM.ActiveCfg = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|ARM.Build.0 = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|x64.ActiveCfg = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|x64.Build.0 = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|x86.ActiveCfg = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|x86.Build.0 = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|Any CPU.Build.0 = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|ARM.ActiveCfg = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|ARM.Build.0 = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|x64.ActiveCfg = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|x64.Build.0 = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|x86.ActiveCfg = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|x86.Build.0 = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|ARM.ActiveCfg = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|ARM.Build.0 = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|x64.ActiveCfg = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|x64.Build.0 = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|x86.ActiveCfg = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|x86.Build.0 = Debug|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|Any CPU.Build.0 = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|ARM.ActiveCfg = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|ARM.Build.0 = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|x64.ActiveCfg = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|x64.Build.0 = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|x86.ActiveCfg = Release|Any CPU - {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|x86.Build.0 = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|ARM.ActiveCfg = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|ARM.Build.0 = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|x64.ActiveCfg = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|x64.Build.0 = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|x86.ActiveCfg = Debug|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|x86.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 - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|ARM.ActiveCfg = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|ARM.Build.0 = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|x64.ActiveCfg = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|x64.Build.0 = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|x86.ActiveCfg = Release|Any CPU - {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|x86.Build.0 = Release|Any CPU - {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 = {554906B2-5972-4EBF-9DD5-EEFA77D735D8} - EndGlobalSection -EndGlobal diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj index ce0cc63fc0..cc13296fe9 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj @@ -1,8 +1,9 @@ - netcoreapp1.1 + netcoreapp2.0 UnitsNet.Serialization.JsonNet.CompatibilityTests + 7.3 diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 95c2d6467d..4f7084831d 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -1,8 +1,9 @@  - netcoreapp1.1 + netcoreapp2.0 UnitsNet.Serialization.JsonNet.Tests + 7.3 diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs index b6c77c84af..4514d5be1d 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -121,12 +121,8 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() [Fact] public void NullValue_ExpectJsonContainsNullString() { - Mass? nullMass = null; - var expectedJson = "null"; - - string json = SerializeObject(nullMass); - - Assert.Equal(expectedJson, json); + string json = SerializeObject(null); + Assert.Equal("null", json); } [Fact] @@ -242,7 +238,7 @@ public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() 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); } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props deleted file mode 100644 index d459f6833a..0000000000 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Common.props +++ /dev/null @@ -1,43 +0,0 @@ - - - - UnitsNet.Serialization.JsonNet - 1.3.1 - Andreas Gullberg Larsen - Units.NET Serialization with Json.NET - A helper library for serializing and deserializing types in Units.NET using Json.NET. - Copyright (c) 2015 Andreas Gullberg Larsen - true - true - true - https://github.com/angularsen/UnitsNet - https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png - https://github.com/angularsen/UnitsNet - https://github.com/angularsen/UnitsNet/blob/master/LICENSE - false - unit units measurement json Json.NET Newtonsoft serialize deserialize serialization deserialization - - - - - netstandard1.0;net35;net40 - UnitsNet.Serialization.JsonNet - - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client - CS1701;CS1702;CS1705;CS0618 - - - - - - - - - - - - - - - - diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj deleted file mode 100644 index 3460bf9f9f..0000000000 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - UnitsNet.Serialization.JsonNet.Signed - Units.NET Serialization with Json.NET (signed) - DEPRECATED - DEPRECATED! Use UnitsNet.Serialization.JsonNet 4.0.0 or later instead, which is now signed. This package will be unlisted sometime later. A helper library for serializing and deserializing types in Units.NET using Json.NET. - - - - - SIGNED - true - $(MSBuildProjectDirectory)\..\UnitsNet.snk - - - - - - - diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index e2f31d9cec..41c83e9d19 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -1,7 +1,52 @@ - - + + + + UnitsNet.Serialization.JsonNet + 4.0.0-beta2 + Andreas Gullberg Larsen + Units.NET Serialization with Json.NET + A helper library for serializing and deserializing types in Units.NET using Json.NET. + Copyright (c) 2015 Andreas Gullberg Larsen + true + https://github.com/angularsen/UnitsNet + https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png + https://github.com/angularsen/UnitsNet + https://github.com/angularsen/UnitsNet/blob/master/LICENSE + false + unit units measurement json Json.NET Newtonsoft serialize deserialize serialization deserialization + - + + + 4.0.0.0 + 7.3 + CS1701;CS1702;CS1705;CS0618 + UnitsNet.Serialization.JsonNet + netstandard2.0;net40 + + + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + + + + + ../UnitsNet.snk + false + true + + + + + + + + + + diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs index f80cc16cc5..27f99eff09 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs @@ -26,6 +26,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnitsNet.Serialization.JsonNet.Internal; +using UnitsNet.Units; namespace UnitsNet.Serialization.JsonNet { @@ -129,9 +130,7 @@ private static object CreateQuantity(Type quantityType, double value, object uni object quantityValue = GetFromMethodValueArgument(notNullableFromMethod, value); // Ex: Mass.From(55, MassUnit.Gram) - // TODO: there is a possible loss of precision if base value requires higher precision than double can represent. - // Example: Serializing Information.FromExabytes(100) then deserializing to Information - // will likely return a very different result. Not sure how we can handle this? + // See ValueUnit about precision loss for quantities using decimal type. return notNullableFromMethod.Invoke(null, new[] {quantityValue, unitValue}); } @@ -206,7 +205,7 @@ public override void WriteJson(JsonWriter writer, object obj, JsonSerializer ser serializer.Serialize(writer, new ValueUnit { - // TODO Should we serialize long, decimal and long differently? + // See ValueUnit about precision loss for quantities using decimal type. Value = Convert.ToDouble(quantityValue), Unit = quantityUnitName }); @@ -232,9 +231,7 @@ private static object GetValueOfQuantity(object value, Type quantityType) { FieldInfo valueField = GetPrivateInstanceField(quantityType, ValueFieldName); - // Unit base type can be double, long or decimal, - // so make sure we serialize the real type to avoid - // loss of precision + // See ValueUnit about precision loss for quantities using decimal type. object quantityValue = valueField.GetValue(value); return quantityValue; } @@ -277,10 +274,13 @@ private static FieldInfo GetPrivateInstanceField(Type quantityType, string field /// A structure used to serialize/deserialize Units.NET unit instances. /// /// - /// TODO Units may use decimal, long or double as base value type and might result + /// 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 { diff --git a/UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp_TemporaryKey.pfx b/UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp_TemporaryKey.pfx deleted file mode 100644 index f9430b979e..0000000000 Binary files a/UnitsNet.TestApps.Uwp.Csharp/UnitsNet.TestApps.Uwp.Csharp_TemporaryKey.pfx and /dev/null differ diff --git a/UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS_TemporaryKey.pfx b/UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS_TemporaryKey.pfx deleted file mode 100644 index 69ade5ebf1..0000000000 Binary files a/UnitsNet.TestApps.Uwp.WinJS/UnitsNet.TestApps.Uwp.WinJS_TemporaryKey.pfx and /dev/null differ diff --git a/UnitsNet.TestApps.sln b/UnitsNet.TestApps.sln deleted file mode 100644 index 1cd5c2919c..0000000000 --- a/UnitsNet.TestApps.sln +++ /dev/null @@ -1,63 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2027 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.TestApps.Uwp.Csharp", "UnitsNet.TestApps.Uwp.Csharp\UnitsNet.TestApps.Uwp.Csharp.csproj", "{76255CC9-A854-441F-AF5C-2606509D3C5E}" -EndProject -Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "UnitsNet.TestApps.Uwp.WinJS", "UnitsNet.TestApps.Uwp.WinJS\UnitsNet.TestApps.Uwp.WinJS.jsproj", "{F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {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|x64 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x64.Build.0 = Debug|x64 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x64.Deploy.0 = Debug|x64 - {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|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|x64 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x64.Build.0 = Release|x64 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x64.Deploy.0 = Release|x64 - {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|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|x64 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x64.Build.0 = Debug|x64 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x64.Deploy.0 = Debug|x64 - {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|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|x64 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x64.Build.0 = Release|x64 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x64.Deploy.0 = Release|x64 - {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 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C28E940D-1A2A-43AC-BF2D-5BF50546156F} - EndGlobalSection -EndGlobal diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index 7e553f92bc..cf90732786 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -12,7 +12,7 @@ public static void EqualTolerance(double expected, double actual, double toleran { if(comparisonType == ComparisonType.Relative) { - bool areEqual = UnitsNet.Comparison.EqualsRelative(expected, actual, tolerance); + bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); double difference = Math.Abs(expected - actual); double relativeDifference = difference / expected; @@ -21,7 +21,7 @@ public static void EqualTolerance(double expected, double actual, double toleran } else if( comparisonType == ComparisonType.Absolute ) { - bool areEqual = UnitsNet.Comparison.EqualsAbsolute(expected, actual, tolerance); + 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/BaseDimensionsTests.cs b/UnitsNet.Tests/BaseDimensionsTests.cs index 3d35b0c00d..f147649381 100644 --- a/UnitsNet.Tests/BaseDimensionsTests.cs +++ b/UnitsNet.Tests/BaseDimensionsTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Xunit; namespace UnitsNet.Tests @@ -6,13 +7,135 @@ namespace UnitsNet.Tests public class BaseDimensionsTests { [Fact] - public void EqualityWorksAsExpected() + public void ConstructorImplementedCorrectly() + { + var baseDimensions = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + Assert.True(baseDimensions.Length == 1); + Assert.True(baseDimensions.Mass == 2); + Assert.True(baseDimensions.Time == 3); + Assert.True(baseDimensions.Current == 4); + Assert.True(baseDimensions.Temperature == 5); + Assert.True(baseDimensions.Amount == 6); + Assert.True(baseDimensions.LuminousIntensity == 7); + } + + [Theory] + [InlineData(1, 0, 0, 0, 0, 0, 0)] + [InlineData(0, 1, 0, 0, 0, 0, 0)] + [InlineData(0, 0, 1, 0, 0, 0, 0)] + [InlineData(0, 0, 0, 1, 0, 0, 0)] + [InlineData(0, 0, 0, 0, 1, 0, 0)] + [InlineData(0, 0, 0, 0, 0, 1, 0)] + [InlineData(0, 0, 0, 0, 0, 0, 1)] + public void IsBaseQuantityImplementedProperly(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity) + { + var baseDimensions = new BaseDimensions(length, mass, time, current, temperature, amount, luminousIntensity); + var derivedDimensions = new BaseDimensions(length * 2, mass * 2, time * 2, current * 2, temperature * 2, amount * 2, luminousIntensity * 2); + + Assert.True(baseDimensions.IsBaseQuantity()); + Assert.False(derivedDimensions.IsBaseQuantity()); + } + + [Theory] + [InlineData(2, 0, 0, 0, 0, 0, 0)] + [InlineData(0, 2, 0, 0, 0, 0, 0)] + [InlineData(0, 0, 2, 0, 0, 0, 0)] + [InlineData(0, 0, 0, 2, 0, 0, 0)] + [InlineData(0, 0, 0, 0, 2, 0, 0)] + [InlineData(0, 0, 0, 0, 0, 2, 0)] + [InlineData(0, 0, 0, 0, 0, 0, 2)] + public void IsDerivedQuantityImplementedProperly(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity) + { + var baseDimensions = new BaseDimensions(length / 2, mass / 2, time / 2, current / 2, temperature / 2, amount / 2, luminousIntensity / 2); + var derivedDimensions = new BaseDimensions(length, mass, time, current, temperature, amount, luminousIntensity); + + Assert.False(baseDimensions.IsDerivedQuantity()); + Assert.True(derivedDimensions.IsDerivedQuantity()); + } + + [Fact] + public void EqualsWorksAsExpected() { var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); Assert.True(baseDimensions1.Equals(baseDimensions2)); Assert.True(baseDimensions2.Equals(baseDimensions1)); + + Assert.False(baseDimensions1.Equals(null)); + } + + [Fact] + public void EqualityOperatorsWorkAsExpected() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + Assert.True(baseDimensions1 == baseDimensions2); + Assert.True(baseDimensions2 == baseDimensions1); + + Assert.False(baseDimensions1 == null); + Assert.False(null == baseDimensions1); + + Assert.False(baseDimensions2 == null); + Assert.False(null == baseDimensions2); + + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; + + Assert.True(nullBaseDimensions1 == nullBaseDimensions2); + } + + [Fact] + public void InequalityOperatorsWorkAsExpected() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + + Assert.True(baseDimensions1 != baseDimensions2); + Assert.True(baseDimensions2 != baseDimensions1); + + Assert.True(baseDimensions1 != null); + Assert.True(null != baseDimensions1); + + Assert.True(baseDimensions2 != null); + Assert.True(null != baseDimensions2); + + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; + + Assert.False(nullBaseDimensions1 != nullBaseDimensions2); + } + + [Fact] + public void MultiplyThrowsExceptionIfPassedNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Multiply(null)); + } + + [Fact] + public void DivideThrowsExceptionIfPassedNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Divide(null)); + } + + [Fact] + public void MultiplyOperatorThrowsExceptionWithNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 / null); + Assert.Throws(() => null / baseDimensions1); + } + + [Fact] + public void DivideOperatorThrowsExceptionWithNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 * null); + Assert.Throws(() => null * baseDimensions1); } [Fact] @@ -576,5 +699,46 @@ public void CheckToStringUsingMolarEntropy() { Assert.Equal("[Length]^2[Mass][Time]^-2[Temperature][Amount]", MolarEntropy.BaseDimensions.ToString()); } + + [Fact] + public void GetHashCodeWorksProperly() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + var baseDimensions3 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + var hashSet = new HashSet(); + + hashSet.Add(baseDimensions1); + Assert.Contains(baseDimensions1, hashSet); + + hashSet.Add(baseDimensions2); + Assert.Contains(baseDimensions2, hashSet); + + // Should be the same as baseDimensions1 + Assert.Contains(baseDimensions3, hashSet); + + Assert.True(baseDimensions1.GetHashCode() != baseDimensions2.GetHashCode()); + Assert.True(baseDimensions1.GetHashCode() == baseDimensions3.GetHashCode()); + } + + [Fact] + public void DimensionlessPropertyIsCorrect() + { + Assert.True(BaseDimensions.Dimensionless == new BaseDimensions(0, 0, 0, 0, 0, 0, 0)); + } + + [Fact] + public void IsDimensionlessMethodImplementedCorrectly() + { + Assert.True(BaseDimensions.Dimensionless.IsDimensionless()); + Assert.True(new BaseDimensions(0, 0, 0, 0, 0, 0, 0).IsDimensionless()); + + Assert.False(BaseDimensions.Dimensionless.IsBaseQuantity()); + Assert.False(BaseDimensions.Dimensionless.IsDerivedQuantity()); + + // Example case + Assert.True(Level.BaseDimensions.IsDimensionless()); + } } } diff --git a/UnitsNet.Tests/BaseUnitsTests.cs b/UnitsNet.Tests/BaseUnitsTests.cs new file mode 100644 index 0000000000..ad3a31370d --- /dev/null +++ b/UnitsNet.Tests/BaseUnitsTests.cs @@ -0,0 +1,121 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests +{ + public class BaseUnitsTests + { + private static BaseUnits siBaseUnits = new BaseUnits(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, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + private static BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + [Fact] + public void ConstructorSetsUnitsProperly() + { + var baseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + Assert.Equal(LengthUnit.Meter, baseUnits.Length); + Assert.Equal(MassUnit.Kilogram, baseUnits.Mass); + Assert.Equal(DurationUnit.Second, baseUnits.Time); + Assert.Equal(ElectricCurrentUnit.Ampere, baseUnits.Current); + Assert.Equal(TemperatureUnit.Kelvin, baseUnits.Temperature); + Assert.Equal(AmountOfSubstanceUnit.Mole, baseUnits.Amount); + Assert.Equal(LuminousIntensityUnit.Candela, baseUnits.LuminousIntensity); + } + + [Fact] + public void EqualsObjectIsImplementedCorrectly() + { + Assert.True(siBaseUnits.Equals((object)siBaseUnitsCopy)); + Assert.False(siBaseUnits.Equals((object)nonSiBaseUnits)); + + 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.False(siBaseUnits.Equals(nonSiBaseUnits)); + Assert.False(nonSiBaseUnits.Equals(siBaseUnits)); + + Assert.False(siBaseUnits.Equals(null)); + } + + [Fact] + public void EqualityOperatorIsImplementedCorrectly() + { + Assert.True(siBaseUnits == siBaseUnitsCopy); + Assert.True(siBaseUnitsCopy == siBaseUnits); + + Assert.False(siBaseUnits == nonSiBaseUnits); + Assert.False(nonSiBaseUnits == siBaseUnits); + + Assert.False(siBaseUnits == null); + Assert.False(null == siBaseUnits); + + BaseUnits nullBaseUnits1 = null; + BaseUnits nullBaseUnits2 = null; + + Assert.True(nullBaseUnits1 == nullBaseUnits2); + } + + [Fact] + public void InequalityOperatorIsImplementedCorrectly() + { + Assert.False(siBaseUnits != siBaseUnitsCopy); + Assert.False(siBaseUnitsCopy != siBaseUnits); + + Assert.True(siBaseUnits != nonSiBaseUnits); + Assert.True(nonSiBaseUnits != siBaseUnits); + + Assert.True(siBaseUnits != null); + Assert.True(null != siBaseUnits); + + BaseUnits nullBaseUnits1 = null; + BaseUnits nullBaseUnits2 = null; + + Assert.False(nullBaseUnits1 != nullBaseUnits2); + } + + [Fact] + public void ToStringGivesExpectedResult() + { + var siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + Assert.Equal("[Length]: m, [Mass]: kg, [Time]: s, [Current]: A, [Temperature]: K, [Amount]: mol, [LuminousIntensity]: cd", siBaseUnits.ToString()); + } + } +} diff --git a/UnitsNet.Tests/CustomCode/AmountOfSubstanceTests.cs b/UnitsNet.Tests/CustomCode/AmountOfSubstanceTests.cs index ef6c3ed41b..d284b7f023 100644 --- a/UnitsNet.Tests/CustomCode/AmountOfSubstanceTests.cs +++ b/UnitsNet.Tests/CustomCode/AmountOfSubstanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs index 9b7482563f..a650941520 100644 --- a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs @@ -21,7 +21,6 @@ using System; using Xunit; -using UnitsNet.CustomCode.Extensions; namespace UnitsNet.Tests.CustomCode { @@ -84,7 +83,7 @@ public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRati // Voltage increases by powers of 10 for every 20 dBV increase in amplitude ratio. AmplitudeRatio ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); - double actual = AmplitudeRatio.ToElectricPotential(ar).Volts; + double actual = ar.ToElectricPotential().Volts; Assert.Equal(expected, actual); } @@ -116,4 +115,4 @@ public void AmplitudeRatioToPowerRatio_75OhmImpedance(double dBmV, double expect Assert.Equal(expected, actual); } } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/ApparentEnergyTests.cs b/UnitsNet.Tests/CustomCode/ApparentEnergyTests.cs index bc236df045..b001be250f 100644 --- a/UnitsNet.Tests/CustomCode/ApparentEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/ApparentEnergyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ApparentPowerTests.cs b/UnitsNet.Tests/CustomCode/ApparentPowerTests.cs index 07a48e333e..066da56e4f 100644 --- a/UnitsNet.Tests/CustomCode/ApparentPowerTests.cs +++ b/UnitsNet.Tests/CustomCode/ApparentPowerTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/AreaDensityTests.cs b/UnitsNet.Tests/CustomCode/AreaDensityTests.cs index 922c143ebb..b6bf0a4f41 100644 --- a/UnitsNet.Tests/CustomCode/AreaDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaDensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/AreaMomentOfInertiaTests.cs b/UnitsNet.Tests/CustomCode/AreaMomentOfInertiaTests.cs index 280bab5459..b19e8aa559 100644 --- a/UnitsNet.Tests/CustomCode/AreaMomentOfInertiaTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaMomentOfInertiaTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/BitRateTests.cs b/UnitsNet.Tests/CustomCode/BitRateTests.cs index 8976f45049..2029c00eca 100644 --- a/UnitsNet.Tests/CustomCode/BitRateTests.cs +++ b/UnitsNet.Tests/CustomCode/BitRateTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs index fbe02ac43f..e141a6ac58 100644 --- a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs +++ b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,7 +21,6 @@ using Xunit; -using System; namespace UnitsNet.Tests.CustomCode { diff --git a/UnitsNet.Tests/CustomCode/CapacitanceTests.cs b/UnitsNet.Tests/CustomCode/CapacitanceTests.cs index e86764476e..a2ab1a95d5 100644 --- a/UnitsNet.Tests/CustomCode/CapacitanceTests.cs +++ b/UnitsNet.Tests/CustomCode/CapacitanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/DensityTests.cs b/UnitsNet.Tests/CustomCode/DensityTests.cs index 6901649b4a..4905088137 100644 --- a/UnitsNet.Tests/CustomCode/DensityTests.cs +++ b/UnitsNet.Tests/CustomCode/DensityTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,9 +19,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; using Xunit; -using UnitsNet.CustomCode.Extensions; namespace UnitsNet.Tests.CustomCode { diff --git a/UnitsNet.Tests/CustomCode/DurationTests.cs b/UnitsNet.Tests/CustomCode/DurationTests.cs index 4ad5c3338e..75249bc3ab 100644 --- a/UnitsNet.Tests/CustomCode/DurationTests.cs +++ b/UnitsNet.Tests/CustomCode/DurationTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,8 +36,6 @@ public class DurationTests : DurationTestsBase protected override double MinutesInOneSecond => 0.0166667; - protected override double MonthsInOneSecond => 3.858024691358024e-7; - protected override double Months30InOneSecond => 3.858024691358024e-7; protected override double NanosecondsInOneSecond => 1e+9; @@ -46,8 +44,6 @@ public class DurationTests : DurationTestsBase protected override double WeeksInOneSecond => 1.653439153439153e-6; - protected override double YearsInOneSecond => 3.170979198376458e-8; - protected override double Years365InOneSecond => 3.170979198376458e-8; [Fact] @@ -180,38 +176,6 @@ public static void DurationGreaterThanOrEqualTimeSpanShouldReturnCorrectly() Assert.True(duration >= timeSpan, "duration should be greater than timeSpan"); } - [Fact] - public static void DurationEqualToTimeSpanShouldReturnCorrectly() - { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(11); - Assert.True(duration == timeSpan, "duration should be equal to timeSpan"); - } - - [Fact] - public static void TimeSpanEqualToDurationShouldReturnCorrectly() - { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(11); - Assert.True(timeSpan == duration, "timeSpan should be equal to duration"); - } - - [Fact] - public static void DurationNotEqualToTimeSpanShouldReturnCorrectly() - { - TimeSpan timeSpan = TimeSpan.FromHours(12); - Duration duration = Duration.FromHours(11); - Assert.True(duration != timeSpan, "duration should not be equal to timeSpan"); - } - - [Fact] - public static void TimeSpanNotEqualToDurationShouldReturnCorrectly() - { - TimeSpan timeSpan = TimeSpan.FromHours(12); - Duration duration = Duration.FromHours(11); - Assert.True(timeSpan != duration, "timeSpan should not be equal to duration"); - } - [Fact] public void DurationTimesVolumeFlowEqualsVolume() { diff --git a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs index f4042366cd..553665afe4 100644 --- a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs +++ b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,7 +20,6 @@ // THE SOFTWARE. -using System; using Xunit; namespace UnitsNet.Tests.CustomCode diff --git a/UnitsNet.Tests/CustomCode/ElectricAdmittanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricAdmittanceTests.cs index f959da1045..835c7855a8 100644 --- a/UnitsNet.Tests/CustomCode/ElectricAdmittanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricAdmittanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricChargeDensityTests.cs b/UnitsNet.Tests/CustomCode/ElectricChargeDensityTests.cs index b5008086dd..abcd5331a1 100644 --- a/UnitsNet.Tests/CustomCode/ElectricChargeDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricChargeDensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricChargeTests.cs b/UnitsNet.Tests/CustomCode/ElectricChargeTests.cs index e2107792e7..98075fb856 100644 --- a/UnitsNet.Tests/CustomCode/ElectricChargeTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricChargeTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricConductanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricConductanceTests.cs index 32ee7dc2ff..fa3cf847dd 100644 --- a/UnitsNet.Tests/CustomCode/ElectricConductanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricConductanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricConductivityTests.cs b/UnitsNet.Tests/CustomCode/ElectricConductivityTests.cs index 10ea9c0615..ac2f37a5e7 100644 --- a/UnitsNet.Tests/CustomCode/ElectricConductivityTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricConductivityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricCurrentDensityTests.cs b/UnitsNet.Tests/CustomCode/ElectricCurrentDensityTests.cs index fd8ab2446f..421f3f14d0 100644 --- a/UnitsNet.Tests/CustomCode/ElectricCurrentDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricCurrentDensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricCurrentGradientTests.cs b/UnitsNet.Tests/CustomCode/ElectricCurrentGradientTests.cs index 937e22b069..9e62a7759c 100644 --- a/UnitsNet.Tests/CustomCode/ElectricCurrentGradientTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricCurrentGradientTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs index c79bf46a8a..92cc98f875 100644 --- a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,8 +19,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; - namespace UnitsNet.Tests.CustomCode { public class ElectricCurrentTests : ElectricCurrentTestsBase diff --git a/UnitsNet.Tests/CustomCode/ElectricFieldTests.cs b/UnitsNet.Tests/CustomCode/ElectricFieldTests.cs index 61e5f68e53..40d8a00324 100644 --- a/UnitsNet.Tests/CustomCode/ElectricFieldTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricFieldTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricInductanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricInductanceTests.cs index 3154f54719..1553851dba 100644 --- a/UnitsNet.Tests/CustomCode/ElectricInductanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricInductanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricPotentialAcTests.cs b/UnitsNet.Tests/CustomCode/ElectricPotentialAcTests.cs index 8a5f7a5cc3..1be6811f5a 100644 --- a/UnitsNet.Tests/CustomCode/ElectricPotentialAcTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricPotentialAcTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricPotentialDcTests.cs b/UnitsNet.Tests/CustomCode/ElectricPotentialDcTests.cs index 56fc31aaa6..80036962cc 100644 --- a/UnitsNet.Tests/CustomCode/ElectricPotentialDcTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricPotentialDcTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/ElectricResistivityTests.cs b/UnitsNet.Tests/CustomCode/ElectricResistivityTests.cs index 8ed53eaeac..0ddb5cc712 100644 --- a/UnitsNet.Tests/CustomCode/ElectricResistivityTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricResistivityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/EnergyTests.cs b/UnitsNet.Tests/CustomCode/EnergyTests.cs index c13006e2f1..3febc639e3 100644 --- a/UnitsNet.Tests/CustomCode/EnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/EnergyTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,7 +23,6 @@ namespace UnitsNet.Tests.CustomCode { public class EnergyTests : EnergyTestsBase { - // TODO Override properties in base class here protected override double ThermsImperialInOneJoule => 9.478171203551087813109937767482e-9; protected override double JoulesInOneJoule => 1; diff --git a/UnitsNet.Tests/CustomCode/EntropyTests.cs b/UnitsNet.Tests/CustomCode/EntropyTests.cs index 69c474b096..9f98fcf392 100644 --- a/UnitsNet.Tests/CustomCode/EntropyTests.cs +++ b/UnitsNet.Tests/CustomCode/EntropyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/FlowTests.cs b/UnitsNet.Tests/CustomCode/FlowTests.cs deleted file mode 100644 index 9742af1064..0000000000 --- a/UnitsNet.Tests/CustomCode/FlowTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace UnitsNet.Tests.CustomCode -{ - public class FlowTests : FlowTestsBase - { - protected override double CubicMetersPerHourInOneCubicMeterPerSecond => 3600.0; - - protected override double CubicDecimetersPerMinuteInOneCubicMeterPerSecond => 60000.00000; - - protected override double CubicFeetPerHourInOneCubicMeterPerSecond => 1.271328001973604e+5; - - protected override double CubicFeetPerSecondInOneCubicMeterPerSecond => 35.314666721489; - - protected override double MillionUsGallonsPerDayInOneCubicMeterPerSecond => 22.824465227; - - protected override double CubicMetersPerSecondInOneCubicMeterPerSecond => 1; - - protected override double UsGallonsPerMinuteInOneCubicMeterPerSecond => 15850.323141489; - protected override double LitersPerHourInOneCubicMeterPerSecond => 3600000; - - protected override double LitersPerMinuteInOneCubicMeterPerSecond => 60000.00000; - - protected override double NanolitersPerMinuteInOneCubicMeterPerSecond => 60000000000000.00000; - protected override double LitersPerSecondInOneCubicMeterPerSecond => 1000; - - protected override double MicrolitersPerMinuteInOneCubicMeterPerSecond => 60000000000.00000; - - protected override double MillilitersPerMinuteInOneCubicMeterPerSecond => 60000000.00000; - - protected override double CentilitersPerMinuteInOneCubicMeterPerSecond => 6000000.00000; - - protected override double DecilitersPerMinuteInOneCubicMeterPerSecond => 600000.00000; - - protected override double KilolitersPerMinuteInOneCubicMeterPerSecond => 60.00000; - - protected override double OilBarrelsPerDayInOneCubicMeterPerSecond => 543439.65056533388306722269588172; - - protected override double CubicFeetPerMinuteInOneCubicMeterPerSecond => 2.11888E3; - - protected override double CubicMetersPerMinuteInOneCubicMeterPerSecond => 6.0E1; - - protected override double CubicYardsPerHourInOneCubicMeterPerSecond => 4.708622232E3; - - protected override double CubicYardsPerMinuteInOneCubicMeterPerSecond => 7.84770372E1; - - protected override double CubicYardsPerSecondInOneCubicMeterPerSecond => 1.30795062; - - protected override double UsGallonsPerHourInOneCubicMeterPerSecond => 9.510193884893328E5; - - protected override double UsGallonsPerSecondInOneCubicMeterPerSecond => 2.64172052358148E2; - } -} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ForceChangeRateTests.cs b/UnitsNet.Tests/CustomCode/ForceChangeRateTests.cs index f745d802aa..8edf0b4aa0 100644 --- a/UnitsNet.Tests/CustomCode/ForceChangeRateTests.cs +++ b/UnitsNet.Tests/CustomCode/ForceChangeRateTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,8 +19,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; - namespace UnitsNet.Tests.CustomCode { public class ForceChangeRateTests : ForceChangeRateTestsBase @@ -37,4 +35,4 @@ public class ForceChangeRateTests : ForceChangeRateTestsBase protected override double MicronewtonsPerSecondInOneNewtonPerSecond => 1E6; protected override double NanonewtonsPerSecondInOneNewtonPerSecond => 1E9; } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/ForcePerLengthTests.cs b/UnitsNet.Tests/CustomCode/ForcePerLengthTests.cs index 38a9735808..5d5b8241b3 100644 --- a/UnitsNet.Tests/CustomCode/ForcePerLengthTests.cs +++ b/UnitsNet.Tests/CustomCode/ForcePerLengthTests.cs @@ -9,7 +9,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/ForceTests.cs b/UnitsNet.Tests/CustomCode/ForceTests.cs index 1e157075fb..305300776b 100644 --- a/UnitsNet.Tests/CustomCode/ForceTests.cs +++ b/UnitsNet.Tests/CustomCode/ForceTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -57,26 +57,19 @@ public void ForceDividedByAreaEqualsPressure() } [Fact] - public void PressureByAreaEqualsForceUsingArea() + public void PressureByAreaEqualsForce() { Force force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(5), Area.FromSquareMeters(7)); Assert.Equal(force, Force.FromNewtons(35)); } - [Fact] - public void PressureByAreaEqualsForceUsingLength2D() - { - var force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(6), Length2d.FromMeters(5, 2)); - Assert.Equal(force, Force.FromNewtons(60)); - } - [Fact] public void ForceDividedByMassEqualsAcceleration() { Acceleration acceleration = Force.FromNewtons(27)/Mass.FromKilograms(9); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(3)); } - + [Fact] public void ForceDividedByAccelerationEqualsMass() { @@ -91,12 +84,6 @@ public void ForceDividedByLengthEqualsForcePerLength() Assert.Equal(forcePerLength, ForcePerLength.FromNewtonsPerMeter(4)); } - [Fact] - public void MassByAccelerationEqualsForceUsingDouble() - { - var force = Force.FromMassByAcceleration(Mass.FromKilograms(9), 3); - Assert.Equal(force, Force.FromNewtons(27)); - } [Fact] public void MassByAccelerationEqualsForce() { diff --git a/UnitsNet.Tests/CustomCode/HeatFluxTests.cs b/UnitsNet.Tests/CustomCode/HeatFluxTests.cs index 6382cb5821..d6633e3eab 100644 --- a/UnitsNet.Tests/CustomCode/HeatFluxTests.cs +++ b/UnitsNet.Tests/CustomCode/HeatFluxTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/HeatTransferCoefficientTests.cs b/UnitsNet.Tests/CustomCode/HeatTransferCoefficientTests.cs index 382367f6a7..80e8eec10f 100644 --- a/UnitsNet.Tests/CustomCode/HeatTransferCoefficientTests.cs +++ b/UnitsNet.Tests/CustomCode/HeatTransferCoefficientTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/IlluminanceTests.cs b/UnitsNet.Tests/CustomCode/IlluminanceTests.cs index b7888ebb4d..3857dd38e8 100644 --- a/UnitsNet.Tests/CustomCode/IlluminanceTests.cs +++ b/UnitsNet.Tests/CustomCode/IlluminanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/IrradianceTests.cs b/UnitsNet.Tests/CustomCode/IrradianceTests.cs index 3ee6591e6b..ec11504bc0 100644 --- a/UnitsNet.Tests/CustomCode/IrradianceTests.cs +++ b/UnitsNet.Tests/CustomCode/IrradianceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/IrradiationTests.cs b/UnitsNet.Tests/CustomCode/IrradiationTests.cs index 555b488d70..4881e68d08 100644 --- a/UnitsNet.Tests/CustomCode/IrradiationTests.cs +++ b/UnitsNet.Tests/CustomCode/IrradiationTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/LapseRateTests.cs b/UnitsNet.Tests/CustomCode/LapseRateTests.cs index 4ae15baa1e..f65015bd56 100644 --- a/UnitsNet.Tests/CustomCode/LapseRateTests.cs +++ b/UnitsNet.Tests/CustomCode/LapseRateTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // @@ -52,14 +51,14 @@ public class LapseRateTests : LapseRateTestsBase [Fact] public void TemperatureDeltaDividedByLapseRateEqualsLength() { - Length length = TemperatureDelta.FromDegreesCelsiusDelta(50) / LapseRate.FromDegreesCelciusPerKilometer(5); + Length length = TemperatureDelta.FromDegreesCelsius(50) / LapseRate.FromDegreesCelciusPerKilometer(5); Assert.Equal(length, Length.FromKilometers(10)); } [Fact] public void TemperatureDeltaDividedByLengthEqualsLapseRate() { - LapseRate lapseRate = TemperatureDelta.FromDegreesCelsiusDelta(50) / Length.FromKilometers(10); + LapseRate lapseRate = TemperatureDelta.FromDegreesCelsius(50) / Length.FromKilometers(10); Assert.Equal(lapseRate, LapseRate.FromDegreesCelciusPerKilometer(5)); } @@ -67,14 +66,14 @@ public void TemperatureDeltaDividedByLengthEqualsLapseRate() public void LengthMultipliedByLapseRateEqualsTemperatureDelta() { TemperatureDelta temperatureDelta = Length.FromKilometers(10) * LapseRate.FromDegreesCelciusPerKilometer(5); - Assert.Equal(temperatureDelta, TemperatureDelta.FromDegreesCelsiusDelta(50)); + Assert.Equal(temperatureDelta, TemperatureDelta.FromDegreesCelsius(50)); } [Fact] public void LapseRateMultipliedByLengthEqualsTemperatureDelta() { TemperatureDelta temperatureDelta = LapseRate.FromDegreesCelciusPerKilometer(5) * Length.FromKilometers(10); - Assert.Equal(temperatureDelta, TemperatureDelta.FromDegreesCelsiusDelta(50)); + Assert.Equal(temperatureDelta, TemperatureDelta.FromDegreesCelsius(50)); } } } diff --git a/UnitsNet.Tests/CustomCode/Length2dTests.cs b/UnitsNet.Tests/CustomCode/Length2dTests.cs deleted file mode 100644 index 06f0b3ff5b..0000000000 --- a/UnitsNet.Tests/CustomCode/Length2dTests.cs +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Xunit; - -namespace UnitsNet.Tests.CustomCode -{ -// ReSharper disable once InconsistentNaming - public class Length2dTests - { - private const double Delta = 1E-5; - - private void AssertAreEqual(Vector2 expected, Vector2 actual, double delta) - { - AssertEx.EqualTolerance(expected.X, actual.X, Delta); - AssertEx.EqualTolerance(expected.Y, actual.Y, Delta); - } - - - [Fact] - public void ArithmeticOperators() - { - Length2d v = Length2d.FromMeters(1, 2); - AssertEx.EqualTolerance(-1, -v.Meters.X, Delta); - AssertEx.EqualTolerance(-2, -v.Meters.Y, Delta); - AssertEx.EqualTolerance(2, (Length2d.FromMeters(3, 3) - v).Meters.X, Delta); - AssertEx.EqualTolerance(1, (Length2d.FromMeters(3, 3) - v).Meters.Y, Delta); - AssertEx.EqualTolerance(2, (v + v).Meters.X, Delta); - AssertEx.EqualTolerance(4, (v + v).Meters.Y, Delta); - AssertEx.EqualTolerance(10, (v*10).Meters.X, Delta); - AssertEx.EqualTolerance(20, (v*10).Meters.Y, Delta); - AssertEx.EqualTolerance(10, (10*v).Meters.X, Delta); - AssertEx.EqualTolerance(20, (10*v).Meters.Y, Delta); - AssertEx.EqualTolerance(2, (Length2d.FromMeters(2, 2)*v).Meters.X, Delta); - AssertEx.EqualTolerance(4, (Length2d.FromMeters(2, 2)*v).Meters.Y, Delta); - AssertEx.EqualTolerance(2, (Length2d.FromMeters(10, 20)/5).Meters.X, Delta); - AssertEx.EqualTolerance(4, (Length2d.FromMeters(10, 20)/5).Meters.Y, Delta); - AssertEx.EqualTolerance(2, (Length2d.FromMeters(10, 20)/Length2d.FromMeters(5, 5)).X, Delta); - AssertEx.EqualTolerance(4, (Length2d.FromMeters(10, 20)/Length2d.FromMeters(5, 5)).Y, Delta); - } - - [Fact] - public void DistanceUnitsRoundTrip() - { - Length meter = Length.FromMeters(1); - - AssertEx.EqualTolerance(1, Length.FromKilometers(meter.Kilometers).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromMeters(meter.Meters).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromDecimeters(meter.Decimeters).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromCentimeters(meter.Centimeters).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromMillimeters(meter.Millimeters).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromMicrometers(meter.Micrometers).Meters, Delta); - AssertEx.EqualTolerance(1, Length.FromNanometers(meter.Nanometers).Meters, Delta); - } - - [Fact] - public void EqualityOperators() - { - Length2d a = Length2d.FromMeters(1, 2); - Length2d b = Length2d.FromMeters(2, 1); - - // ReSharper disable EqualExpressionComparison - // Disable build warning: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -#pragma warning restore 1718 - // ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Length2d v = Length2d.FromMeters(1, 2); - Assert.True(v.Equals(Length2d.FromMeters(1, 2))); - Assert.False(v.Equals(Length2d.Zero)); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Length2d newton = Length2d.FromMeters(1, 2); - Assert.False(newton.Equals(null)); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Length2d newton = Length2d.FromMeters(1, 2); - Assert.False(newton.Equals(new object())); - } - - [Fact] - public void MetersToDistanceUnits() - { - Length2d meter = Length2d.FromMeters(1, 1); - - AssertAreEqual(new Vector2(1), meter.Meters, Delta); - AssertAreEqual(new Vector2(1E2), meter.Centimeters, Delta); - AssertAreEqual(new Vector2(1E3), meter.Millimeters, Delta); - AssertAreEqual(new Vector2(1E-3), meter.Kilometers, Delta); - AssertAreEqual(new Vector2(1), meter.Meters, Delta); - AssertAreEqual(new Vector2(1E1), meter.Decimeters, Delta); - AssertAreEqual(new Vector2(1E2), meter.Centimeters, Delta); - AssertAreEqual(new Vector2(1E3), meter.Millimeters, Delta); - AssertAreEqual(new Vector2(1E6), meter.Micrometers, Delta); - AssertAreEqual(new Vector2(1E9), meter.Nanometers, Delta); - - AssertEx.EqualTolerance(0.000621371, meter.Miles.X, Delta); - AssertEx.EqualTolerance(0.000621371, meter.Miles.Y, Delta); - AssertEx.EqualTolerance(1.09361, meter.Yards.X, Delta); - AssertEx.EqualTolerance(1.09361, meter.Yards.Y, Delta); - AssertEx.EqualTolerance(3.28084, meter.Feet.X, Delta); - AssertEx.EqualTolerance(3.28084, meter.Feet.Y, Delta); - AssertEx.EqualTolerance(39.37007874, meter.Inches.X, Delta); - AssertEx.EqualTolerance(39.37007874, meter.Inches.Y, Delta); - } - - [Fact] - public void VectorLength() - { - var v = new Length2d(3, 4); - Assert.Equal(5, v.Length.Meters); - } - } -} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/FeetInchesTests.cs b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs similarity index 54% rename from UnitsNet.Tests/CustomCode/FeetInchesTests.cs rename to UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs index 73dd817f8e..715a655fed 100644 --- a/UnitsNet.Tests/CustomCode/FeetInchesTests.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -46,5 +46,46 @@ public void FeetInchesRoundTrip() AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); } + + [Theory] + [InlineData("1'", 1)] // Feet only + [InlineData("1′", 1)] // Feet only + [InlineData("1\"", 0.08333333)] // Inches only + [InlineData("1″", 0.08333333)] // Inches only + [InlineData("1' 1\"", 1.08333333)] // Normal form + [InlineData("1′ 1″", 1.08333333)] // Normal form + [InlineData(" 1′ 1″ ", 1.08333333)] // Normal form, requires trimming + [InlineData("1'1\"", 1.08333333)] // Without space + [InlineData("1′1″", 1.08333333)] // Without space + [InlineData("1 ft 1 in", 1.08333333)] + [InlineData("1ft 1in", 1.08333333)] + public void TryParseFeetInches(string str, double expectedFeet) + { + Assert.True(Length.TryParseFeetInches(str, out Length result)); + AssertEx.EqualTolerance(expectedFeet, result.Feet, 1e-5); + } + + [Theory] + [InlineData("a")] // Missing or invalid apostrophe or double prime chars + [InlineData("1")] + [InlineData("1`")] + [InlineData("1^")] + [InlineData("1' 1'")] // Feet apostrophe twice + [InlineData("1′ 1′")] + [InlineData("1' 1")] // No inches double prime + [InlineData("1′ 1")] + [InlineData("1′ 1`")] // Invalid inches double prime + [InlineData("1' 1`")] + [InlineData("1'1'")] // Same without space + [InlineData("1′1′")] + [InlineData("1'1")] + [InlineData("1′1")] + [InlineData("1′1`")] + [InlineData("1'1`")] + public void TryParseFeetInches_GivenInvalidString_ReturnsFalseAndZeroOut(string str) + { + Assert.False(Length.TryParseFeetInches(str, out Length result)); + Assert.Equal(Length.Zero, result); + } } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/LengthTests.cs b/UnitsNet.Tests/CustomCode/LengthTests.cs index 9b64a25383..df789dbdca 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,7 +19,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; using Xunit; using UnitsNet.Units; @@ -28,7 +27,7 @@ namespace UnitsNet.Tests.CustomCode // Avoid accessing static prop DefaultToString in parallel from multiple tests: // UnitSystemTests.DefaultToStringFormatting() // LengthTests.ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() - [Collection(nameof(UnitSystemFixture))] + [Collection(nameof(UnitAbbreviationsCacheFixture))] public class LengthTests : LengthTestsBase { protected override double CentimetersInOneMeter => 100; @@ -61,7 +60,7 @@ public class LengthTests : LengthTestsBase protected override double NanometersInOneMeter => 1E9; protected override double YardsInOneMeter => 1.09361; - + protected override double FathomsInOneMeter => 0.546806649; protected override double PrinterPicasInOneMeter => 237.10630158; @@ -130,22 +129,16 @@ public void LengthTimesSpecificWeightEqualsPressure() [Fact] public void ToStringReturnsCorrectNumberAndUnitWithDefaultUnitWhichIsMeter() { - LengthUnit oldUnit = Length.ToStringDefaultUnit; - Length.ToStringDefaultUnit = LengthUnit.Meter; - Length meter = Length.FromMeters(5); + var meter = Length.FromMeters(5); string meterString = meter.ToString(); - Length.ToStringDefaultUnit = oldUnit; Assert.Equal("5 m", meterString); } [Fact] public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() { - LengthUnit oldUnit = Length.ToStringDefaultUnit; - Length.ToStringDefaultUnit = LengthUnit.Centimeter; - Length value = Length.From(2, LengthUnit.Centimeter); + var value = Length.From(2, LengthUnit.Centimeter); string valueString = value.ToString(); - Length.ToStringDefaultUnit = oldUnit; Assert.Equal("2 cm", valueString); } diff --git a/UnitsNet.Tests/CustomCode/LinearDensityTests.cs b/UnitsNet.Tests/CustomCode/LinearDensityTests.cs index 12a3e096d7..dba00a625b 100644 --- a/UnitsNet.Tests/CustomCode/LinearDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/LinearDensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/LuminousFluxTests.cs b/UnitsNet.Tests/CustomCode/LuminousFluxTests.cs index 28249e44b2..bcffaaaa54 100644 --- a/UnitsNet.Tests/CustomCode/LuminousFluxTests.cs +++ b/UnitsNet.Tests/CustomCode/LuminousFluxTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/LuminousIntensityTests.cs b/UnitsNet.Tests/CustomCode/LuminousIntensityTests.cs index e5628edd65..f23f7f7901 100644 --- a/UnitsNet.Tests/CustomCode/LuminousIntensityTests.cs +++ b/UnitsNet.Tests/CustomCode/LuminousIntensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MagneticFieldTests.cs b/UnitsNet.Tests/CustomCode/MagneticFieldTests.cs index 84574014f7..8aa59ffb31 100644 --- a/UnitsNet.Tests/CustomCode/MagneticFieldTests.cs +++ b/UnitsNet.Tests/CustomCode/MagneticFieldTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MagneticFluxTests.cs b/UnitsNet.Tests/CustomCode/MagneticFluxTests.cs index 40cf6c214f..647cc7e9d4 100644 --- a/UnitsNet.Tests/CustomCode/MagneticFluxTests.cs +++ b/UnitsNet.Tests/CustomCode/MagneticFluxTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MagnetizationTests.cs b/UnitsNet.Tests/CustomCode/MagnetizationTests.cs index d2be75815d..bb4ab57af1 100644 --- a/UnitsNet.Tests/CustomCode/MagnetizationTests.cs +++ b/UnitsNet.Tests/CustomCode/MagnetizationTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MassFluxTests.cs b/UnitsNet.Tests/CustomCode/MassFluxTests.cs index 797e0f01aa..18ff2333d8 100644 --- a/UnitsNet.Tests/CustomCode/MassFluxTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFluxTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MassMomentOfInertiaTests.cs b/UnitsNet.Tests/CustomCode/MassMomentOfInertiaTests.cs index fb6722c264..79c3cae71e 100644 --- a/UnitsNet.Tests/CustomCode/MassMomentOfInertiaTests.cs +++ b/UnitsNet.Tests/CustomCode/MassMomentOfInertiaTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/MolarEnergyTests.cs b/UnitsNet.Tests/CustomCode/MolarEnergyTests.cs index 3bf535be10..b9aaf18adf 100644 --- a/UnitsNet.Tests/CustomCode/MolarEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/MolarEnergyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MolarEntropyTests.cs b/UnitsNet.Tests/CustomCode/MolarEntropyTests.cs index 1b24dd86bf..b8a012804f 100644 --- a/UnitsNet.Tests/CustomCode/MolarEntropyTests.cs +++ b/UnitsNet.Tests/CustomCode/MolarEntropyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MolarMassTests.cs b/UnitsNet.Tests/CustomCode/MolarMassTests.cs index d05b1e8f40..231ecab43e 100644 --- a/UnitsNet.Tests/CustomCode/MolarMassTests.cs +++ b/UnitsNet.Tests/CustomCode/MolarMassTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/MolarityTests.cs b/UnitsNet.Tests/CustomCode/MolarityTests.cs index 305fa12c2d..92ebb8735e 100644 --- a/UnitsNet.Tests/CustomCode/MolarityTests.cs +++ b/UnitsNet.Tests/CustomCode/MolarityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // @@ -42,7 +41,6 @@ using Xunit; using System; -using UnitsNet.CustomCode.Extensions; namespace UnitsNet.Tests.CustomCode { diff --git a/UnitsNet.Tests/CustomCode/ParseTests.cs b/UnitsNet.Tests/CustomCode/ParseTests.cs index 3fb03de1a0..294c12d0e1 100644 --- a/UnitsNet.Tests/CustomCode/ParseTests.cs +++ b/UnitsNet.Tests/CustomCode/ParseTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,8 +21,8 @@ using System; using System.Globalization; -using Xunit; using UnitsNet.Units; +using Xunit; namespace UnitsNet.Tests.CustomCode { @@ -33,10 +33,12 @@ namespace UnitsNet.Tests.CustomCode /// reasonable to assume that testing one unit class would cover /// all of them. Obviously, that can change in the future. /// + [Collection(nameof(UnitAbbreviationsCacheFixture))] public class ParseTests { [Theory] [InlineData("1km", 1000)] + [InlineData(" 1km ", 1000)] // Check that it also trims string [InlineData("1 km", 1000)] [InlineData("1e-3 km", 1)] [InlineData("5.5 m", 5.5)] @@ -49,31 +51,16 @@ public void ParseLengthToMetersUsEnglish(string s, double expected) } [Theory] - [InlineData(null, "System.ArgumentNullException")] // Can't parse null. - [InlineData("1", "System.ArgumentException")] // No unit abbreviation. - [InlineData("km", "UnitsNet.UnitsNetException")] // No value, wrong measurement type. - [InlineData("1 kg", "UnitsNet.UnitsNetException")] // Wrong measurement type. - [InlineData("1ft monkey 1in", "UnitsNet.UnitsNetException")] // Invalid separator between two valid measurements. - [InlineData("1ft 1invalid", "UnitsNet.UnitsNetException")] // Valid - public void ParseLength_InvalidString_USEnglish_ThrowsException(string s, string expected) - { - CultureInfo usEnglish = new CultureInfo("en-US"); - string actual = AssertExceptionAndGetFullTypeName(() => Length.Parse(s, usEnglish)); - Assert.Equal(expected, actual); - } - - [Theory] - [InlineData("1 ft 1 in", 13)] - [InlineData("1ft 1in", 13)] - [InlineData("1' 1\"", 13)] - [InlineData("1'1\"", 13)] - [InlineData("1ft1in", 13)] - [InlineData("1ft and 1in", 13)] - public void ParseLength_FeetInchesString_USEnglish(string s, double expected) + [InlineData(null, typeof(ArgumentNullException))] // Can't parse null. + [InlineData("1", typeof(FormatException))] // No unit abbreviation. + [InlineData("km", typeof(FormatException))] // No value, wrong measurement type. + [InlineData("1 kg", typeof(FormatException))] // Wrong measurement type. + [InlineData("1ft monkey 1in", typeof(FormatException))] // Invalid separator between two valid measurements. + [InlineData("1ft 1invalid", typeof(FormatException))] // Valid + public void ParseLength_InvalidString_USEnglish_ThrowsException(string s, Type expectedExceptionType) { - CultureInfo usEnglish = new CultureInfo("en-US"); - double actual = Length.Parse(s, usEnglish).Inches; - Assert.Equal(expected, actual); + var usEnglish = new CultureInfo("en-US"); + Assert.Throws(expectedExceptionType, () => Length.Parse(s, usEnglish)); } /// Error parsing string. @@ -85,23 +72,26 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, double expe { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = " "; + numberFormat.CurrencyGroupSeparator = " "; numberFormat.NumberDecimalSeparator = "."; + numberFormat.CurrencyDecimalSeparator = "."; double actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } [Theory] - [InlineData("500.005.050,001 m", "UnitsNet.UnitsNetException")] + [InlineData("500.005.050,001 m", typeof(FormatException))] // quantity doesn't match number format - public void ParseWithCultureUsingSpaceAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, string expected) + public void ParseWithCultureUsingSpaceAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, Type expectedExceptionType) { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = " "; + numberFormat.CurrencyGroupSeparator = " "; numberFormat.NumberDecimalSeparator = "."; + numberFormat.CurrencyDecimalSeparator = "."; - string actual = AssertExceptionAndGetFullTypeName(() => Length.Parse(s, numberFormat)); - Assert.Equal(expected, actual); + Assert.Throws(expectedExceptionType, () => Length.Parse(s, numberFormat)); } /// Error parsing string. @@ -113,7 +103,9 @@ public void ParseWithCultureUsingDotAsThousandSeparators(string s, double expect { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = "."; + numberFormat.CurrencyGroupSeparator = "."; numberFormat.NumberDecimalSeparator = ","; + numberFormat.CurrencyDecimalSeparator = ","; double actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); @@ -127,15 +119,16 @@ public void ParseMultiWordAbbreviations() } [Theory] - [InlineData("500 005 m", "UnitsNet.UnitsNetException")] // Quantity doesn't match number format. - public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, string expected) + [InlineData("500 005 m", typeof(FormatException))] // Quantity doesn't match number format. + public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, Type expectedExceptionType) { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = "."; + numberFormat.CurrencyGroupSeparator = "."; numberFormat.NumberDecimalSeparator = ","; + numberFormat.CurrencyDecimalSeparator = ","; - string actual = AssertExceptionAndGetFullTypeName(() => Length.Parse(s, numberFormat)); - Assert.Equal(expected, actual); + Assert.Throws(expectedExceptionType, () => Length.Parse(s, numberFormat)); } [Theory] @@ -148,18 +141,17 @@ public void ParseLengthUnitUsEnglish(string s, LengthUnit expected) } [Theory] - [InlineData("kg", "UnitsNet.UnitNotFoundException")] - [InlineData(null, "System.ArgumentNullException")] - public void ParseLengthUnitUsEnglish_ThrowsExceptionOnInvalidString(string s, string expected) + [InlineData("kg", typeof(UnitNotFoundException))] + [InlineData(null, typeof(ArgumentNullException))] + public void ParseLengthUnitUsEnglish_ThrowsExceptionOnInvalidString(string s, Type expectedExceptionType) { - CultureInfo usEnglish = new CultureInfo("en-US"); - string actual = AssertExceptionAndGetFullTypeName(() => Length.ParseUnit(s, usEnglish)); - Assert.Equal(expected, actual); + var usEnglish = new CultureInfo("en-US"); + Assert.Throws(expectedExceptionType, () => Length.ParseUnit(s, usEnglish)); } [Theory] [InlineData("1 m", true)] - [InlineData("1 m 50 cm", true)] + [InlineData("1 m 50 cm", false)] [InlineData("2 kg", false)] [InlineData(null, false)] [InlineData("foo", false)] @@ -169,70 +161,5 @@ public void TryParseLengthUnitUsEnglish(string s, bool expected) bool actual = Length.TryParse(s, usEnglish, out Length _); Assert.Equal(expected, actual); } - - [Theory] - [InlineData("!")] - [InlineData("@")] - [InlineData("#")] - [InlineData("$")] - [InlineData("%")] - [InlineData("^")] - [InlineData("&")] - [InlineData("*")] - [InlineData("-")] - [InlineData("_")] - [InlineData("?")] - [InlineData("123")] - [InlineData(" ")] - public void TryParseLengthUnitAbbreviationSpecialCharacters(string s) - { - string abbrev = $"m{s}s"; - - UnitSystem unitSystem = UnitSystem.GetCached(); - unitSystem.MapUnitToAbbreviation(LengthUnit.Meter, abbrev); - - // Act - bool ok = unitSystem.TryParse(abbrev, out LengthUnit result); - - // Assert - Assert.True(ok, "TryParse " + abbrev); - Assert.Equal(LengthUnit.Meter, result); - } - - [Theory] - [InlineData("!")] - [InlineData("@")] - [InlineData("#")] - [InlineData("$")] - [InlineData("%")] - [InlineData("^")] - [InlineData("&")] - [InlineData("*")] - [InlineData("-")] - [InlineData("_")] - [InlineData("?")] - [InlineData("123")] - [InlineData(" ")] - public void TryParseLengthSpecialCharacters(string s) - { - string abbrev = $"m{s}s"; - - UnitSystem unitSystem = UnitSystem.GetCached(); - unitSystem.MapUnitToAbbreviation(LengthUnit.Meter, abbrev); - - // Act - bool ok = Length.TryParse($"10 {abbrev}", out Length result); - - // Assert - Assert.True(ok, $"TryParse \"10 {abbrev}\""); - Assert.Equal(10, result.Meters); - } - - private static string AssertExceptionAndGetFullTypeName(Action code) - { - var exception = Assert.ThrowsAny(code); - return exception.GetType().FullName; - } - } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/PermeabilityTests.cs b/UnitsNet.Tests/CustomCode/PermeabilityTests.cs index 05a96b3d83..6e111e4400 100644 --- a/UnitsNet.Tests/CustomCode/PermeabilityTests.cs +++ b/UnitsNet.Tests/CustomCode/PermeabilityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/PermittivityTests.cs b/UnitsNet.Tests/CustomCode/PermittivityTests.cs index 71d26f7f1d..9cd30ffd5d 100644 --- a/UnitsNet.Tests/CustomCode/PermittivityTests.cs +++ b/UnitsNet.Tests/CustomCode/PermittivityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/PowerDensityTests.cs b/UnitsNet.Tests/CustomCode/PowerDensityTests.cs index abc3dfac11..39194a47b9 100644 --- a/UnitsNet.Tests/CustomCode/PowerDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerDensityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs index 3229634f59..5d84f0cab3 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -21,7 +21,6 @@ using System; using Xunit; -using UnitsNet.CustomCode.Extensions; namespace UnitsNet.Tests.CustomCode { @@ -72,7 +71,7 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expected) { PowerRatio pr = PowerRatio.FromDecibelWatts(powerRatio); - double actual = PowerRatio.ToPower(pr).Watts; + double actual = pr.ToPower().Watts; Assert.Equal(expected, actual); } @@ -104,4 +103,4 @@ public void PowerRatioToAmplitudeRatio_75OhmImpedance(double dBmW, double expect Assert.Equal(expected, actual); } } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index 89ed3967ae..58dd5cea48 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,7 +19,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; using Xunit; namespace UnitsNet.Tests.CustomCode @@ -66,8 +65,6 @@ public class PressureTests : PressureTestsBase protected override double PoundsForcePerSquareInchInOnePascal => 1.450377377302092e-4; - protected override double PsiInOnePascal => 1.450377377302092e-4; - protected override double TechnicalAtmospheresInOnePascal => 1.0197*1E-5; protected override double TonnesForcePerSquareCentimeterInOnePascal => 1.019716212977928e-8; diff --git a/UnitsNet.Tests/CustomCode/ReactiveEnergyTests.cs b/UnitsNet.Tests/CustomCode/ReactiveEnergyTests.cs index f31bd68f08..8fa7fe3ad5 100644 --- a/UnitsNet.Tests/CustomCode/ReactiveEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/ReactiveEnergyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ReactivePowerTests.cs b/UnitsNet.Tests/CustomCode/ReactivePowerTests.cs index a000168a07..6cf738d778 100644 --- a/UnitsNet.Tests/CustomCode/ReactivePowerTests.cs +++ b/UnitsNet.Tests/CustomCode/ReactivePowerTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/RotationalAccelerationTests.cs b/UnitsNet.Tests/CustomCode/RotationalAccelerationTests.cs index 11b1be4f50..e390d5adc5 100644 --- a/UnitsNet.Tests/CustomCode/RotationalAccelerationTests.cs +++ b/UnitsNet.Tests/CustomCode/RotationalAccelerationTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/RotationalStiffnessPerLengthTests.cs b/UnitsNet.Tests/CustomCode/RotationalStiffnessPerLengthTests.cs index ec848ea3dd..cb77d0f51d 100644 --- a/UnitsNet.Tests/CustomCode/RotationalStiffnessPerLengthTests.cs +++ b/UnitsNet.Tests/CustomCode/RotationalStiffnessPerLengthTests.cs @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------ // // This code was generated (once) by \generate-code.bat, but will not be -// regenerated when it already exists. The purpose of creating this file is to make +// regenerated when it already exists. The purpose of creating this file is to make // it easier to remember to implement all the unit conversion test cases. -// +// // Whenever a new unit is added to this quantity and \generate-code.bat is run, // the base test class will get a new abstract property and cause a compile error // in this derived class, reminding the developer to implement the test case @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // @@ -20,17 +19,17 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -46,8 +45,6 @@ namespace UnitsNet.Tests.CustomCode { public class RotationalStiffnessPerLengthTests : RotationalStiffnessPerLengthTestsBase { - // TODO Override properties in base class here - protected override double KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter => 1E-3; protected override double MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter => 1E-6; protected override double NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter => 1; diff --git a/UnitsNet.Tests/CustomCode/RotationalStiffnessTests.cs b/UnitsNet.Tests/CustomCode/RotationalStiffnessTests.cs index af62b987fd..a1dae7613d 100644 --- a/UnitsNet.Tests/CustomCode/RotationalStiffnessTests.cs +++ b/UnitsNet.Tests/CustomCode/RotationalStiffnessTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/SolidAngleTests.cs b/UnitsNet.Tests/CustomCode/SolidAngleTests.cs index 0b0fde3e05..523833f0b3 100644 --- a/UnitsNet.Tests/CustomCode/SolidAngleTests.cs +++ b/UnitsNet.Tests/CustomCode/SolidAngleTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/SpecificEntropyTests.cs b/UnitsNet.Tests/CustomCode/SpecificEntropyTests.cs index d3417e7e43..7c928f8f52 100644 --- a/UnitsNet.Tests/CustomCode/SpecificEntropyTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificEntropyTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/SpecificVolumeTests.cs b/UnitsNet.Tests/CustomCode/SpecificVolumeTests.cs index 49d9dbf222..7f5ced0f45 100644 --- a/UnitsNet.Tests/CustomCode/SpecificVolumeTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificVolumeTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/TemperatureDeltaTests.cs b/UnitsNet.Tests/CustomCode/TemperatureDeltaTests.cs index d1254bc451..a4f51502d4 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureDeltaTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureDeltaTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // @@ -45,15 +44,6 @@ namespace UnitsNet.Tests.CustomCode { public class TemperatureDeltaTests : TemperatureDeltaTestsBase { - protected override double DegreesCelsiusDeltaInOneKelvin => 1; - protected override double DegreesDelisleDeltaInOneKelvin => -1.5d; - protected override double DegreesFahrenheitDeltaInOneKelvin => 1.8; - protected override double DegreesNewtonDeltaInOneKelvin => 0.33d; - protected override double DegreesRankineDeltaInOneKelvin => 1.8; - protected override double DegreesReaumurDeltaInOneKelvin => 0.8; - protected override double DegreesRoemerDeltaInOneKelvin => 21/40d; - protected override double KelvinsDeltaInOneKelvin => 1; - protected override double DegreesCelsiusInOneKelvin => 1; protected override double DegreesDelisleInOneKelvin => -1.5d; protected override double DegreesFahrenheitInOneKelvin => 1.8; diff --git a/UnitsNet.Tests/CustomCode/TemperatureTests.cs b/UnitsNet.Tests/CustomCode/TemperatureTests.cs index ad2c029b78..0aa5f9d234 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -61,7 +61,7 @@ public void DividedByTemperatureDeltaEqualsTemperature(TemperatureUnit unit, int // Act Temperature resultTemp = temperature.Divide(divisor, unit); - string actual = resultTemp.ToString(unit, CultureInfo.InvariantCulture, "{0:0} {1}"); + string actual = resultTemp.ToUnit(unit).ToString(CultureInfo.InvariantCulture, "{0:0} {1}"); Assert.Equal(expected, actual); } @@ -81,7 +81,7 @@ public void MultiplyByTemperatureDeltaEqualsTemperature(TemperatureUnit unit, in // Act Temperature resultTemp = temperature.Multiply(factor, unit); - string actual = resultTemp.ToString(unit, CultureInfo.InvariantCulture, "{0:0} {1}"); + string actual = resultTemp.ToUnit(unit).ToString(CultureInfo.InvariantCulture, "{0:0} {1}"); Assert.Equal(expected, actual); } @@ -100,7 +100,7 @@ public void TemperatureDeltaPlusTemperatureEqualsTemperature(TemperatureUnit uni // Act Temperature resultTemp = delta + temperature; - string actual = resultTemp.ToString(unit, CultureInfo.InvariantCulture, "{0:0} {1}"); + string actual = resultTemp.ToUnit(unit).ToString(CultureInfo.InvariantCulture, "{0:0} {1}"); Assert.Equal(expected, actual); } @@ -119,7 +119,7 @@ public void TemperatureMinusTemperatureDeltaEqualsTemperature(TemperatureUnit un // Act Temperature resultTemp = temperature - delta; - string actual = resultTemp.ToString(unit, CultureInfo.InvariantCulture, "{0:0} {1}"); + string actual = resultTemp.ToUnit(unit).ToString(CultureInfo.InvariantCulture, "{0:0} {1}"); Assert.Equal(expected, actual); } @@ -138,8 +138,8 @@ public void TemperaturePlusTemperatureDeltaEqualsTemperature(TemperatureUnit uni // Act Temperature resultTemp = temperature + delta; - string actual = resultTemp.ToString(unit, CultureInfo.InvariantCulture, "{0:0} {1}"); + string actual = resultTemp.ToUnit(unit).ToString(CultureInfo.InvariantCulture, "{0:0} {1}"); Assert.Equal(expected, actual); } } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/CustomCode/ThermalConductivityTests.cs b/UnitsNet.Tests/CustomCode/ThermalConductivityTests.cs index 469f727fe2..1a4f97977d 100644 --- a/UnitsNet.Tests/CustomCode/ThermalConductivityTests.cs +++ b/UnitsNet.Tests/CustomCode/ThermalConductivityTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/ThermalResistanceTests.cs b/UnitsNet.Tests/CustomCode/ThermalResistanceTests.cs index 44d65ef57f..2cba064ee4 100644 --- a/UnitsNet.Tests/CustomCode/ThermalResistanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ThermalResistanceTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\UnitClasses\MyQuantity.extra.cs files to add code to generated unit classes. -// Add Extensions\MyQuantityExtensions.cs to decorate unit classes with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or unit classes. // // diff --git a/UnitsNet.Tests/CustomCode/VolumeFlowTests.cs b/UnitsNet.Tests/CustomCode/VolumeFlowTests.cs index bc88c7dff3..1eb1ff61d1 100644 --- a/UnitsNet.Tests/CustomCode/VolumeFlowTests.cs +++ b/UnitsNet.Tests/CustomCode/VolumeFlowTests.cs @@ -12,7 +12,6 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // diff --git a/UnitsNet.Tests/CustomCode/VolumeTests.cs b/UnitsNet.Tests/CustomCode/VolumeTests.cs index c64002bcbb..34f3f7900c 100644 --- a/UnitsNet.Tests/CustomCode/VolumeTests.cs +++ b/UnitsNet.Tests/CustomCode/VolumeTests.cs @@ -77,25 +77,17 @@ public class VolumeTests : VolumeTestsBase protected override double AuTablespoonsInOneCubicMeter => 50000; protected override double UsTablespoonsInOneCubicMeter => 67628.0454; - - protected override double TablespoonsInOneCubicMeter => 67628.0454; - - protected override double TablespoonsTolerance => 1E-4; protected override double MetricTeaspoonsInOneCubicMeter => 200000; protected override double UsTeaspoonsInOneCubicMeter => 202884.13621105801; - protected override double TeaspoonsInOneCubicMeter => 202884.13621105801; - protected override double ImperialBeerBarrelsInOneCubicMeter => 6.1102568972; protected override double UkTablespoonsInOneCubicMeter => 66666.6666667; protected override double UsBeerBarrelsInOneCubicMeter => 8.5216790723083; - protected override double TeaspoonsTolerance => 1E-3; - protected override double UsGallonsInOneCubicMeter => 264.17217; protected override double UsOuncesInOneCubicMeter => 33814.02270; diff --git a/UnitsNet.Tests/DecimalOverloadTests.cs b/UnitsNet.Tests/DecimalOverloadTests.cs index f19e131a14..6865026af6 100644 --- a/UnitsNet.Tests/DecimalOverloadTests.cs +++ b/UnitsNet.Tests/DecimalOverloadTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,8 +20,6 @@ // THE SOFTWARE. using Xunit; -using UnitsNet.Extensions.NumberToAcceleration; -using UnitsNet.Extensions.NumberToPower; namespace UnitsNet.Tests { @@ -30,101 +28,15 @@ public class DecimalOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorrectValue() { - decimal oneMeterPerSecondSquared = 1m; - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1m); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableDecimalReturnsCorrectValue() - { - decimal? oneMeterPerSecondSquared = 1m; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableDecimalReturnsNullWhenGivenNull() - { - decimal? nullDecimal = null; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(nullDecimal); - Assert.Null(acceleration); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromDecimalWithExtensionMethodReturnsCorrectValue() - { - decimal oneMeterPerSecondSquared = 1m; - Acceleration acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.Equal(1.0, acceleration.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableDecimalWithExtensionMethodReturnsCorrectValue() - { - decimal? oneMeterPerSecondSquared = 1m; - Acceleration? acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableDecimalWithExtensionMethodReturnsNullWhenGivenNull() - { - decimal? nullDecimal = null; - Acceleration? acceleration = nullDecimal.MetersPerSecondSquared(); - Assert.Null(acceleration); - } - [Fact] public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() { - decimal oneWatt = 1m; - Power power = Power.FromWatts(oneWatt); + Power power = Power.FromWatts(1m); Assert.Equal(1.0, power.Watts); } - - [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromNullableDecimalReturnsCorrectValue() - { - decimal? oneWatt = 1m; - Power? power = Power.FromWatts(oneWatt); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromNullableDecimalReturnsNullWhenGivenNull() - { - decimal? nullDecimal = null; - Power? power = Power.FromWatts(nullDecimal); - Assert.Null(power); - } - - [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromDecimalWithExtensionMethodReturnsCorrectValue() - { - decimal oneWatt = 1m; - Power power = oneWatt.Watts(); - Assert.Equal(1.0, power.Watts); - } - - [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromNullableDecimalWithExtensionMethodReturnsCorrectValue() - { - decimal? oneWatt = 1m; - Power? power = oneWatt.Watts(); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromNullableDecimalWithExtensionMethodReturnsNullWhenGivenNull() - { - decimal? nullDecimal = null; - Power? power = nullDecimal.Watts(); - Assert.Null(power); - } } } diff --git a/UnitsNet.Tests/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensionsTest.cs b/UnitsNet.Tests/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensionsTest.cs deleted file mode 100644 index de5e702403..0000000000 --- a/UnitsNet.Tests/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensionsTest.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using Xunit; -using UnitsNet.Extensions.NumberToTimeSpan; - -namespace UnitsNet.Tests.Extensions.NumberToTimeSpan -{ - public class NumberToTimeSpanExtensionsTest - { - [Fact] - public void ExtensionMethodsReturnTimeSpanOfSameValue() - { - Assert.Equal(TimeSpan.FromDays(1), 1.d()); - Assert.Equal(TimeSpan.FromDays(1), 1L.d()); - Assert.Equal(TimeSpan.FromDays(1), 1f.d()); - Assert.Equal(TimeSpan.FromDays(1), 1d.d()); - Assert.Equal(TimeSpan.FromDays(1), 1m.d()); - - Assert.Equal(TimeSpan.FromHours(1), 1.h()); - Assert.Equal(TimeSpan.FromHours(1), 1L.h()); - Assert.Equal(TimeSpan.FromHours(1), 1f.h()); - Assert.Equal(TimeSpan.FromHours(1), 1d.h()); - Assert.Equal(TimeSpan.FromHours(1), 1m.h()); - - Assert.Equal(TimeSpan.FromMinutes(1), 1.m()); - Assert.Equal(TimeSpan.FromMinutes(1), 1L.m()); - Assert.Equal(TimeSpan.FromMinutes(1), 1f.m()); - Assert.Equal(TimeSpan.FromMinutes(1), 1d.m()); - Assert.Equal(TimeSpan.FromMinutes(1), 1m.m()); - - Assert.Equal(TimeSpan.FromSeconds(1), 1.s()); - Assert.Equal(TimeSpan.FromSeconds(1), 1L.s()); - Assert.Equal(TimeSpan.FromSeconds(1), 1f.s()); - Assert.Equal(TimeSpan.FromSeconds(1), 1d.s()); - Assert.Equal(TimeSpan.FromSeconds(1), 1m.s()); - - Assert.Equal(TimeSpan.FromMilliseconds(1), 1.ms()); - Assert.Equal(TimeSpan.FromMilliseconds(1), 1L.ms()); - Assert.Equal(TimeSpan.FromMilliseconds(1), 1f.ms()); - Assert.Equal(TimeSpan.FromMilliseconds(1), 1d.ms()); - Assert.Equal(TimeSpan.FromMilliseconds(1), 1m.ms()); - } - } -} diff --git a/UnitsNet.Tests/GeneratedCode/.gitignore b/UnitsNet.Tests/GeneratedCode/.gitignore new file mode 100644 index 0000000000..6dd350f428 --- /dev/null +++ b/UnitsNet.Tests/GeneratedCode/.gitignore @@ -0,0 +1,4 @@ +*.g.cs +!InformationTestsBase.g.cs +!LengthTestsBase.g.cs +!LevelTestsBase.g.cs diff --git a/UnitsNet.Tests/GeneratedCode/AccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AccelerationTestsBase.g.cs deleted file mode 100644 index 6312872176..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AccelerationTestsBase.g.cs +++ /dev/null @@ -1,317 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Acceleration. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AccelerationTestsBase - { - protected abstract double CentimetersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double DecimetersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double FeetPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double InchesPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double KilometersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double KnotsPerHourInOneMeterPerSecondSquared { get; } - protected abstract double KnotsPerMinuteInOneMeterPerSecondSquared { get; } - protected abstract double KnotsPerSecondInOneMeterPerSecondSquared { get; } - protected abstract double MetersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double MicrometersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double MillimetersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double NanometersPerSecondSquaredInOneMeterPerSecondSquared { get; } - protected abstract double StandardGravityInOneMeterPerSecondSquared { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double FeetPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double InchesPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double KilometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double KnotsPerHourTolerance { get { return 1e-5; } } - protected virtual double KnotsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KnotsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double NanometersPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double StandardGravityTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void MeterPerSecondSquaredToAccelerationUnits() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(CentimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(DecimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(FeetPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - AssertEx.EqualTolerance(InchesPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(KilometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(KnotsPerHourInOneMeterPerSecondSquared, meterpersecondsquared.KnotsPerHour, KnotsPerHourTolerance); - AssertEx.EqualTolerance(KnotsPerMinuteInOneMeterPerSecondSquared, meterpersecondsquared.KnotsPerMinute, KnotsPerMinuteTolerance); - AssertEx.EqualTolerance(KnotsPerSecondInOneMeterPerSecondSquared, meterpersecondsquared.KnotsPerSecond, KnotsPerSecondTolerance); - AssertEx.EqualTolerance(MetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(MicrometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(MillimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(NanometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(StandardGravityInOneMeterPerSecondSquared, meterpersecondsquared.StandardGravity, StandardGravityTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.CentimeterPerSecondSquared).CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.DecimeterPerSecondSquared).DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.FootPerSecondSquared).FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.InchPerSecondSquared).InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.KilometerPerSecondSquared).KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.KnotPerHour).KnotsPerHour, KnotsPerHourTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.KnotPerMinute).KnotsPerMinute, KnotsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.KnotPerSecond).KnotsPerSecond, KnotsPerSecondTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.MeterPerSecondSquared).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.MicrometerPerSecondSquared).MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.MillimeterPerSecondSquared).MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.NanometerPerSecondSquared).NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.From(1, AccelerationUnit.StandardGravity).StandardGravity, StandardGravityTolerance); - } - - [Fact] - public void As() - { - var meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(CentimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.CentimeterPerSecondSquared), CentimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(DecimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.DecimeterPerSecondSquared), DecimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(FeetPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.FootPerSecondSquared), FeetPerSecondSquaredTolerance); - AssertEx.EqualTolerance(InchesPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.InchPerSecondSquared), InchesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(KilometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.KilometerPerSecondSquared), KilometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(KnotsPerHourInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.KnotPerHour), KnotsPerHourTolerance); - AssertEx.EqualTolerance(KnotsPerMinuteInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.KnotPerMinute), KnotsPerMinuteTolerance); - AssertEx.EqualTolerance(KnotsPerSecondInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.KnotPerSecond), KnotsPerSecondTolerance); - AssertEx.EqualTolerance(MetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.MeterPerSecondSquared), MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(MicrometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.MicrometerPerSecondSquared), MicrometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(MillimetersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.MillimeterPerSecondSquared), MillimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(NanometersPerSecondSquaredInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.NanometerPerSecondSquared), NanometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(StandardGravityInOneMeterPerSecondSquared, meterpersecondsquared.As(AccelerationUnit.StandardGravity), StandardGravityTolerance); - } - - [Fact] - public void ToUnit() - { - var meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - - var centimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.CentimeterPerSecondSquared); - AssertEx.EqualTolerance(CentimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)centimeterpersecondsquaredQuantity.Value, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, centimeterpersecondsquaredQuantity.Unit); - - var decimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.DecimeterPerSecondSquared); - AssertEx.EqualTolerance(DecimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)decimeterpersecondsquaredQuantity.Value, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, decimeterpersecondsquaredQuantity.Unit); - - var footpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.FootPerSecondSquared); - AssertEx.EqualTolerance(FeetPerSecondSquaredInOneMeterPerSecondSquared, (double)footpersecondsquaredQuantity.Value, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, footpersecondsquaredQuantity.Unit); - - var inchpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.InchPerSecondSquared); - AssertEx.EqualTolerance(InchesPerSecondSquaredInOneMeterPerSecondSquared, (double)inchpersecondsquaredQuantity.Value, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, inchpersecondsquaredQuantity.Unit); - - var kilometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KilometerPerSecondSquared); - AssertEx.EqualTolerance(KilometersPerSecondSquaredInOneMeterPerSecondSquared, (double)kilometerpersecondsquaredQuantity.Value, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, kilometerpersecondsquaredQuantity.Unit); - - var knotperhourQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerHour); - AssertEx.EqualTolerance(KnotsPerHourInOneMeterPerSecondSquared, (double)knotperhourQuantity.Value, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, knotperhourQuantity.Unit); - - var knotperminuteQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerMinute); - AssertEx.EqualTolerance(KnotsPerMinuteInOneMeterPerSecondSquared, (double)knotperminuteQuantity.Value, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, knotperminuteQuantity.Unit); - - var knotpersecondQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.KnotPerSecond); - AssertEx.EqualTolerance(KnotsPerSecondInOneMeterPerSecondSquared, (double)knotpersecondQuantity.Value, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, knotpersecondQuantity.Unit); - - var meterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MeterPerSecondSquared); - AssertEx.EqualTolerance(MetersPerSecondSquaredInOneMeterPerSecondSquared, (double)meterpersecondsquaredQuantity.Value, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, meterpersecondsquaredQuantity.Unit); - - var micrometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MicrometerPerSecondSquared); - AssertEx.EqualTolerance(MicrometersPerSecondSquaredInOneMeterPerSecondSquared, (double)micrometerpersecondsquaredQuantity.Value, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, micrometerpersecondsquaredQuantity.Unit); - - var millimeterpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.MillimeterPerSecondSquared); - AssertEx.EqualTolerance(MillimetersPerSecondSquaredInOneMeterPerSecondSquared, (double)millimeterpersecondsquaredQuantity.Value, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, millimeterpersecondsquaredQuantity.Unit); - - var nanometerpersecondsquaredQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.NanometerPerSecondSquared); - AssertEx.EqualTolerance(NanometersPerSecondSquaredInOneMeterPerSecondSquared, (double)nanometerpersecondsquaredQuantity.Value, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, nanometerpersecondsquaredQuantity.Unit); - - var standardgravityQuantity = meterpersecondsquared.ToUnit(AccelerationUnit.StandardGravity); - AssertEx.EqualTolerance(StandardGravityInOneMeterPerSecondSquared, (double)standardgravityQuantity.Value, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, standardgravityQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(1, Acceleration.FromCentimetersPerSecondSquared(meterpersecondsquared.CentimetersPerSecondSquared).MetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromDecimetersPerSecondSquared(meterpersecondsquared.DecimetersPerSecondSquared).MetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromFeetPerSecondSquared(meterpersecondsquared.FeetPerSecondSquared).MetersPerSecondSquared, FeetPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromInchesPerSecondSquared(meterpersecondsquared.InchesPerSecondSquared).MetersPerSecondSquared, InchesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKilometersPerSecondSquared(meterpersecondsquared.KilometersPerSecondSquared).MetersPerSecondSquared, KilometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerHour(meterpersecondsquared.KnotsPerHour).MetersPerSecondSquared, KnotsPerHourTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerMinute(meterpersecondsquared.KnotsPerMinute).MetersPerSecondSquared, KnotsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerSecond(meterpersecondsquared.KnotsPerSecond).MetersPerSecondSquared, KnotsPerSecondTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMetersPerSecondSquared(meterpersecondsquared.MetersPerSecondSquared).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMicrometersPerSecondSquared(meterpersecondsquared.MicrometersPerSecondSquared).MetersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMillimetersPerSecondSquared(meterpersecondsquared.MillimetersPerSecondSquared).MetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromNanometersPerSecondSquared(meterpersecondsquared.NanometersPerSecondSquared).MetersPerSecondSquared, NanometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromStandardGravity(meterpersecondsquared.StandardGravity).MetersPerSecondSquared, StandardGravityTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Acceleration v = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(-1, -v.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (Acceleration.FromMetersPerSecondSquared(3)-v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (Acceleration.FromMetersPerSecondSquared(10)/5).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, Acceleration.FromMetersPerSecondSquared(10)/Acceleration.FromMetersPerSecondSquared(5), MetersPerSecondSquaredTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Acceleration oneMeterPerSecondSquared = Acceleration.FromMetersPerSecondSquared(1); - Acceleration twoMetersPerSecondSquared = Acceleration.FromMetersPerSecondSquared(2); - - Assert.True(oneMeterPerSecondSquared < twoMetersPerSecondSquared); - Assert.True(oneMeterPerSecondSquared <= twoMetersPerSecondSquared); - Assert.True(twoMetersPerSecondSquared > oneMeterPerSecondSquared); - Assert.True(twoMetersPerSecondSquared >= oneMeterPerSecondSquared); - - Assert.False(oneMeterPerSecondSquared > twoMetersPerSecondSquared); - Assert.False(oneMeterPerSecondSquared >= twoMetersPerSecondSquared); - Assert.False(twoMetersPerSecondSquared < oneMeterPerSecondSquared); - Assert.False(twoMetersPerSecondSquared <= oneMeterPerSecondSquared); - } - - [Fact] - public void CompareToIsImplemented() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - Assert.Equal(0, meterpersecondsquared.CompareTo(meterpersecondsquared)); - Assert.True(meterpersecondsquared.CompareTo(Acceleration.Zero) > 0); - Assert.True(Acceleration.Zero.CompareTo(meterpersecondsquared) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - Assert.Throws(() => meterpersecondsquared.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - Assert.Throws(() => meterpersecondsquared.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Acceleration a = Acceleration.FromMetersPerSecondSquared(1); - Acceleration b = Acceleration.FromMetersPerSecondSquared(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Acceleration v = Acceleration.FromMetersPerSecondSquared(1); - Assert.True(v.Equals(Acceleration.FromMetersPerSecondSquared(1), Acceleration.FromMetersPerSecondSquared(MetersPerSecondSquaredTolerance))); - Assert.False(v.Equals(Acceleration.Zero, Acceleration.FromMetersPerSecondSquared(MetersPerSecondSquaredTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - Assert.False(meterpersecondsquared.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - Assert.False(meterpersecondsquared.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AccelerationUnit.Undefined, Acceleration.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AmountOfSubstanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AmountOfSubstanceTestsBase.g.cs deleted file mode 100644 index 8e81e74de8..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AmountOfSubstanceTestsBase.g.cs +++ /dev/null @@ -1,337 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of AmountOfSubstance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AmountOfSubstanceTestsBase - { - protected abstract double CentimolesInOneMole { get; } - protected abstract double CentipoundMolesInOneMole { get; } - protected abstract double DecimolesInOneMole { get; } - protected abstract double DecipoundMolesInOneMole { get; } - protected abstract double KilomolesInOneMole { get; } - protected abstract double KilopoundMolesInOneMole { get; } - protected abstract double MegamolesInOneMole { get; } - protected abstract double MicromolesInOneMole { get; } - protected abstract double MicropoundMolesInOneMole { get; } - protected abstract double MillimolesInOneMole { get; } - protected abstract double MillipoundMolesInOneMole { get; } - protected abstract double MolesInOneMole { get; } - protected abstract double NanomolesInOneMole { get; } - protected abstract double NanopoundMolesInOneMole { get; } - protected abstract double PoundMolesInOneMole { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimolesTolerance { get { return 1e-5; } } - protected virtual double CentipoundMolesTolerance { get { return 1e-5; } } - protected virtual double DecimolesTolerance { get { return 1e-5; } } - protected virtual double DecipoundMolesTolerance { get { return 1e-5; } } - protected virtual double KilomolesTolerance { get { return 1e-5; } } - protected virtual double KilopoundMolesTolerance { get { return 1e-5; } } - protected virtual double MegamolesTolerance { get { return 1e-5; } } - protected virtual double MicromolesTolerance { get { return 1e-5; } } - protected virtual double MicropoundMolesTolerance { get { return 1e-5; } } - protected virtual double MillimolesTolerance { get { return 1e-5; } } - protected virtual double MillipoundMolesTolerance { get { return 1e-5; } } - protected virtual double MolesTolerance { get { return 1e-5; } } - protected virtual double NanomolesTolerance { get { return 1e-5; } } - protected virtual double NanopoundMolesTolerance { get { return 1e-5; } } - protected virtual double PoundMolesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void MoleToAmountOfSubstanceUnits() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(CentimolesInOneMole, mole.Centimoles, CentimolesTolerance); - AssertEx.EqualTolerance(CentipoundMolesInOneMole, mole.CentipoundMoles, CentipoundMolesTolerance); - AssertEx.EqualTolerance(DecimolesInOneMole, mole.Decimoles, DecimolesTolerance); - AssertEx.EqualTolerance(DecipoundMolesInOneMole, mole.DecipoundMoles, DecipoundMolesTolerance); - AssertEx.EqualTolerance(KilomolesInOneMole, mole.Kilomoles, KilomolesTolerance); - AssertEx.EqualTolerance(KilopoundMolesInOneMole, mole.KilopoundMoles, KilopoundMolesTolerance); - AssertEx.EqualTolerance(MegamolesInOneMole, mole.Megamoles, MegamolesTolerance); - AssertEx.EqualTolerance(MicromolesInOneMole, mole.Micromoles, MicromolesTolerance); - AssertEx.EqualTolerance(MicropoundMolesInOneMole, mole.MicropoundMoles, MicropoundMolesTolerance); - AssertEx.EqualTolerance(MillimolesInOneMole, mole.Millimoles, MillimolesTolerance); - AssertEx.EqualTolerance(MillipoundMolesInOneMole, mole.MillipoundMoles, MillipoundMolesTolerance); - AssertEx.EqualTolerance(MolesInOneMole, mole.Moles, MolesTolerance); - AssertEx.EqualTolerance(NanomolesInOneMole, mole.Nanomoles, NanomolesTolerance); - AssertEx.EqualTolerance(NanopoundMolesInOneMole, mole.NanopoundMoles, NanopoundMolesTolerance); - AssertEx.EqualTolerance(PoundMolesInOneMole, mole.PoundMoles, PoundMolesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Centimole).Centimoles, CentimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.CentipoundMole).CentipoundMoles, CentipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Decimole).Decimoles, DecimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.DecipoundMole).DecipoundMoles, DecipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Kilomole).Kilomoles, KilomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.KilopoundMole).KilopoundMoles, KilopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Megamole).Megamoles, MegamolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Micromole).Micromoles, MicromolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.MicropoundMole).MicropoundMoles, MicropoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Millimole).Millimoles, MillimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.MillipoundMole).MillipoundMoles, MillipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Mole).Moles, MolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.Nanomole).Nanomoles, NanomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.NanopoundMole).NanopoundMoles, NanopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.From(1, AmountOfSubstanceUnit.PoundMole).PoundMoles, PoundMolesTolerance); - } - - [Fact] - public void As() - { - var mole = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(CentimolesInOneMole, mole.As(AmountOfSubstanceUnit.Centimole), CentimolesTolerance); - AssertEx.EqualTolerance(CentipoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.CentipoundMole), CentipoundMolesTolerance); - AssertEx.EqualTolerance(DecimolesInOneMole, mole.As(AmountOfSubstanceUnit.Decimole), DecimolesTolerance); - AssertEx.EqualTolerance(DecipoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.DecipoundMole), DecipoundMolesTolerance); - AssertEx.EqualTolerance(KilomolesInOneMole, mole.As(AmountOfSubstanceUnit.Kilomole), KilomolesTolerance); - AssertEx.EqualTolerance(KilopoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.KilopoundMole), KilopoundMolesTolerance); - AssertEx.EqualTolerance(MegamolesInOneMole, mole.As(AmountOfSubstanceUnit.Megamole), MegamolesTolerance); - AssertEx.EqualTolerance(MicromolesInOneMole, mole.As(AmountOfSubstanceUnit.Micromole), MicromolesTolerance); - AssertEx.EqualTolerance(MicropoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.MicropoundMole), MicropoundMolesTolerance); - AssertEx.EqualTolerance(MillimolesInOneMole, mole.As(AmountOfSubstanceUnit.Millimole), MillimolesTolerance); - AssertEx.EqualTolerance(MillipoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.MillipoundMole), MillipoundMolesTolerance); - AssertEx.EqualTolerance(MolesInOneMole, mole.As(AmountOfSubstanceUnit.Mole), MolesTolerance); - AssertEx.EqualTolerance(NanomolesInOneMole, mole.As(AmountOfSubstanceUnit.Nanomole), NanomolesTolerance); - AssertEx.EqualTolerance(NanopoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.NanopoundMole), NanopoundMolesTolerance); - AssertEx.EqualTolerance(PoundMolesInOneMole, mole.As(AmountOfSubstanceUnit.PoundMole), PoundMolesTolerance); - } - - [Fact] - public void ToUnit() - { - var mole = AmountOfSubstance.FromMoles(1); - - var centimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Centimole); - AssertEx.EqualTolerance(CentimolesInOneMole, (double)centimoleQuantity.Value, CentimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Centimole, centimoleQuantity.Unit); - - var centipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.CentipoundMole); - AssertEx.EqualTolerance(CentipoundMolesInOneMole, (double)centipoundmoleQuantity.Value, CentipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.CentipoundMole, centipoundmoleQuantity.Unit); - - var decimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Decimole); - AssertEx.EqualTolerance(DecimolesInOneMole, (double)decimoleQuantity.Value, DecimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Decimole, decimoleQuantity.Unit); - - var decipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.DecipoundMole); - AssertEx.EqualTolerance(DecipoundMolesInOneMole, (double)decipoundmoleQuantity.Value, DecipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.DecipoundMole, decipoundmoleQuantity.Unit); - - var kilomoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Kilomole); - AssertEx.EqualTolerance(KilomolesInOneMole, (double)kilomoleQuantity.Value, KilomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Kilomole, kilomoleQuantity.Unit); - - var kilopoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.KilopoundMole); - AssertEx.EqualTolerance(KilopoundMolesInOneMole, (double)kilopoundmoleQuantity.Value, KilopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.KilopoundMole, kilopoundmoleQuantity.Unit); - - var megamoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Megamole); - AssertEx.EqualTolerance(MegamolesInOneMole, (double)megamoleQuantity.Value, MegamolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Megamole, megamoleQuantity.Unit); - - var micromoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Micromole); - AssertEx.EqualTolerance(MicromolesInOneMole, (double)micromoleQuantity.Value, MicromolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Micromole, micromoleQuantity.Unit); - - var micropoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.MicropoundMole); - AssertEx.EqualTolerance(MicropoundMolesInOneMole, (double)micropoundmoleQuantity.Value, MicropoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MicropoundMole, micropoundmoleQuantity.Unit); - - var millimoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Millimole); - AssertEx.EqualTolerance(MillimolesInOneMole, (double)millimoleQuantity.Value, MillimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Millimole, millimoleQuantity.Unit); - - var millipoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.MillipoundMole); - AssertEx.EqualTolerance(MillipoundMolesInOneMole, (double)millipoundmoleQuantity.Value, MillipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MillipoundMole, millipoundmoleQuantity.Unit); - - var moleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Mole); - AssertEx.EqualTolerance(MolesInOneMole, (double)moleQuantity.Value, MolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Mole, moleQuantity.Unit); - - var nanomoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.Nanomole); - AssertEx.EqualTolerance(NanomolesInOneMole, (double)nanomoleQuantity.Value, NanomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Nanomole, nanomoleQuantity.Unit); - - var nanopoundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.NanopoundMole); - AssertEx.EqualTolerance(NanopoundMolesInOneMole, (double)nanopoundmoleQuantity.Value, NanopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.NanopoundMole, nanopoundmoleQuantity.Unit); - - var poundmoleQuantity = mole.ToUnit(AmountOfSubstanceUnit.PoundMole); - AssertEx.EqualTolerance(PoundMolesInOneMole, (double)poundmoleQuantity.Value, PoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.PoundMole, poundmoleQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromCentimoles(mole.Centimoles).Moles, CentimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromCentipoundMoles(mole.CentipoundMoles).Moles, CentipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromDecimoles(mole.Decimoles).Moles, DecimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromDecipoundMoles(mole.DecipoundMoles).Moles, DecipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromKilomoles(mole.Kilomoles).Moles, KilomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromKilopoundMoles(mole.KilopoundMoles).Moles, KilopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMegamoles(mole.Megamoles).Moles, MegamolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMicromoles(mole.Micromoles).Moles, MicromolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMicropoundMoles(mole.MicropoundMoles).Moles, MicropoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMillimoles(mole.Millimoles).Moles, MillimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMillipoundMoles(mole.MillipoundMoles).Moles, MillipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMoles(mole.Moles).Moles, MolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromNanomoles(mole.Nanomoles).Moles, NanomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromNanopoundMoles(mole.NanopoundMoles).Moles, NanopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromPoundMoles(mole.PoundMoles).Moles, PoundMolesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - AmountOfSubstance v = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(-1, -v.Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (AmountOfSubstance.FromMoles(3)-v).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (v + v).Moles, MolesTolerance); - AssertEx.EqualTolerance(10, (v*10).Moles, MolesTolerance); - AssertEx.EqualTolerance(10, (10*v).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (AmountOfSubstance.FromMoles(10)/5).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, AmountOfSubstance.FromMoles(10)/AmountOfSubstance.FromMoles(5), MolesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - AmountOfSubstance oneMole = AmountOfSubstance.FromMoles(1); - AmountOfSubstance twoMoles = AmountOfSubstance.FromMoles(2); - - Assert.True(oneMole < twoMoles); - Assert.True(oneMole <= twoMoles); - Assert.True(twoMoles > oneMole); - Assert.True(twoMoles >= oneMole); - - Assert.False(oneMole > twoMoles); - Assert.False(oneMole >= twoMoles); - Assert.False(twoMoles < oneMole); - Assert.False(twoMoles <= oneMole); - } - - [Fact] - public void CompareToIsImplemented() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - Assert.Equal(0, mole.CompareTo(mole)); - Assert.True(mole.CompareTo(AmountOfSubstance.Zero) > 0); - Assert.True(AmountOfSubstance.Zero.CompareTo(mole) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - Assert.Throws(() => mole.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - Assert.Throws(() => mole.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - AmountOfSubstance a = AmountOfSubstance.FromMoles(1); - AmountOfSubstance b = AmountOfSubstance.FromMoles(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - AmountOfSubstance v = AmountOfSubstance.FromMoles(1); - Assert.True(v.Equals(AmountOfSubstance.FromMoles(1), AmountOfSubstance.FromMoles(MolesTolerance))); - Assert.False(v.Equals(AmountOfSubstance.Zero, AmountOfSubstance.FromMoles(MolesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - Assert.False(mole.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - Assert.False(mole.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AmountOfSubstanceUnit.Undefined, AmountOfSubstance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AmplitudeRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AmplitudeRatioTestsBase.g.cs deleted file mode 100644 index 5ef7153039..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AmplitudeRatioTestsBase.g.cs +++ /dev/null @@ -1,232 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of AmplitudeRatio. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AmplitudeRatioTestsBase - { - protected abstract double DecibelMicrovoltsInOneDecibelVolt { get; } - protected abstract double DecibelMillivoltsInOneDecibelVolt { get; } - protected abstract double DecibelsUnloadedInOneDecibelVolt { get; } - protected abstract double DecibelVoltsInOneDecibelVolt { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecibelMicrovoltsTolerance { get { return 1e-5; } } - protected virtual double DecibelMillivoltsTolerance { get { return 1e-5; } } - protected virtual double DecibelsUnloadedTolerance { get { return 1e-5; } } - protected virtual double DecibelVoltsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DecibelVoltToAmplitudeRatioUnits() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - AssertEx.EqualTolerance(DecibelMicrovoltsInOneDecibelVolt, decibelvolt.DecibelMicrovolts, DecibelMicrovoltsTolerance); - AssertEx.EqualTolerance(DecibelMillivoltsInOneDecibelVolt, decibelvolt.DecibelMillivolts, DecibelMillivoltsTolerance); - AssertEx.EqualTolerance(DecibelsUnloadedInOneDecibelVolt, decibelvolt.DecibelsUnloaded, DecibelsUnloadedTolerance); - AssertEx.EqualTolerance(DecibelVoltsInOneDecibelVolt, decibelvolt.DecibelVolts, DecibelVoltsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelMicrovolt).DecibelMicrovolts, DecibelMicrovoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelMillivolt).DecibelMillivolts, DecibelMillivoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelUnloaded).DecibelsUnloaded, DecibelsUnloadedTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelVolt).DecibelVolts, DecibelVoltsTolerance); - } - - [Fact] - public void As() - { - var decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - AssertEx.EqualTolerance(DecibelMicrovoltsInOneDecibelVolt, decibelvolt.As(AmplitudeRatioUnit.DecibelMicrovolt), DecibelMicrovoltsTolerance); - AssertEx.EqualTolerance(DecibelMillivoltsInOneDecibelVolt, decibelvolt.As(AmplitudeRatioUnit.DecibelMillivolt), DecibelMillivoltsTolerance); - AssertEx.EqualTolerance(DecibelsUnloadedInOneDecibelVolt, decibelvolt.As(AmplitudeRatioUnit.DecibelUnloaded), DecibelsUnloadedTolerance); - AssertEx.EqualTolerance(DecibelVoltsInOneDecibelVolt, decibelvolt.As(AmplitudeRatioUnit.DecibelVolt), DecibelVoltsTolerance); - } - - [Fact] - public void ToUnit() - { - var decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - - var decibelmicrovoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelMicrovolt); - AssertEx.EqualTolerance(DecibelMicrovoltsInOneDecibelVolt, (double)decibelmicrovoltQuantity.Value, DecibelMicrovoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, decibelmicrovoltQuantity.Unit); - - var decibelmillivoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelMillivolt); - AssertEx.EqualTolerance(DecibelMillivoltsInOneDecibelVolt, (double)decibelmillivoltQuantity.Value, DecibelMillivoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMillivolt, decibelmillivoltQuantity.Unit); - - var decibelunloadedQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelUnloaded); - AssertEx.EqualTolerance(DecibelsUnloadedInOneDecibelVolt, (double)decibelunloadedQuantity.Value, DecibelsUnloadedTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelUnloaded, decibelunloadedQuantity.Unit); - - var decibelvoltQuantity = decibelvolt.ToUnit(AmplitudeRatioUnit.DecibelVolt); - AssertEx.EqualTolerance(DecibelVoltsInOneDecibelVolt, (double)decibelvoltQuantity.Value, DecibelVoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelVolt, decibelvoltQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelMicrovolts(decibelvolt.DecibelMicrovolts).DecibelVolts, DecibelMicrovoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelMillivolts(decibelvolt.DecibelMillivolts).DecibelVolts, DecibelMillivoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelsUnloaded(decibelvolt.DecibelsUnloaded).DecibelVolts, DecibelsUnloadedTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelVolts(decibelvolt.DecibelVolts).DecibelVolts, DecibelVoltsTolerance); - } - - [Fact] - public void LogarithmicArithmeticOperators() - { - AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); - AssertEx.EqualTolerance(-40, -v.DecibelVolts, DecibelVoltsTolerance); - AssertLogarithmicAddition(); - AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(50, (10*v).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(35, (v/5).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(35, v/AmplitudeRatio.FromDecibelVolts(5), DecibelVoltsTolerance); - } - - protected abstract void AssertLogarithmicAddition(); - - protected abstract void AssertLogarithmicSubtraction(); - - - [Fact] - public void ComparisonOperators() - { - AmplitudeRatio oneDecibelVolt = AmplitudeRatio.FromDecibelVolts(1); - AmplitudeRatio twoDecibelVolts = AmplitudeRatio.FromDecibelVolts(2); - - Assert.True(oneDecibelVolt < twoDecibelVolts); - Assert.True(oneDecibelVolt <= twoDecibelVolts); - Assert.True(twoDecibelVolts > oneDecibelVolt); - Assert.True(twoDecibelVolts >= oneDecibelVolt); - - Assert.False(oneDecibelVolt > twoDecibelVolts); - Assert.False(oneDecibelVolt >= twoDecibelVolts); - Assert.False(twoDecibelVolts < oneDecibelVolt); - Assert.False(twoDecibelVolts <= oneDecibelVolt); - } - - [Fact] - public void CompareToIsImplemented() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.Equal(0, decibelvolt.CompareTo(decibelvolt)); - Assert.True(decibelvolt.CompareTo(AmplitudeRatio.Zero) > 0); - Assert.True(AmplitudeRatio.Zero.CompareTo(decibelvolt) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.Throws(() => decibelvolt.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.Throws(() => decibelvolt.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - AmplitudeRatio a = AmplitudeRatio.FromDecibelVolts(1); - AmplitudeRatio b = AmplitudeRatio.FromDecibelVolts(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(1); - Assert.True(v.Equals(AmplitudeRatio.FromDecibelVolts(1), AmplitudeRatio.FromDecibelVolts(DecibelVoltsTolerance))); - Assert.False(v.Equals(AmplitudeRatio.Zero, AmplitudeRatio.FromDecibelVolts(DecibelVoltsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.False(decibelvolt.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.False(decibelvolt.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AmplitudeRatioUnit.Undefined, AmplitudeRatio.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AngleTestsBase.g.cs deleted file mode 100644 index 6589478a78..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AngleTestsBase.g.cs +++ /dev/null @@ -1,327 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Angle. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AngleTestsBase - { - protected abstract double ArcminutesInOneDegree { get; } - protected abstract double ArcsecondsInOneDegree { get; } - protected abstract double CentiradiansInOneDegree { get; } - protected abstract double DeciradiansInOneDegree { get; } - protected abstract double DegreesInOneDegree { get; } - protected abstract double GradiansInOneDegree { get; } - protected abstract double MicrodegreesInOneDegree { get; } - protected abstract double MicroradiansInOneDegree { get; } - protected abstract double MillidegreesInOneDegree { get; } - protected abstract double MilliradiansInOneDegree { get; } - protected abstract double NanodegreesInOneDegree { get; } - protected abstract double NanoradiansInOneDegree { get; } - protected abstract double RadiansInOneDegree { get; } - protected abstract double RevolutionsInOneDegree { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double ArcminutesTolerance { get { return 1e-5; } } - protected virtual double ArcsecondsTolerance { get { return 1e-5; } } - protected virtual double CentiradiansTolerance { get { return 1e-5; } } - protected virtual double DeciradiansTolerance { get { return 1e-5; } } - protected virtual double DegreesTolerance { get { return 1e-5; } } - protected virtual double GradiansTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesTolerance { get { return 1e-5; } } - protected virtual double MicroradiansTolerance { get { return 1e-5; } } - protected virtual double MillidegreesTolerance { get { return 1e-5; } } - protected virtual double MilliradiansTolerance { get { return 1e-5; } } - protected virtual double NanodegreesTolerance { get { return 1e-5; } } - protected virtual double NanoradiansTolerance { get { return 1e-5; } } - protected virtual double RadiansTolerance { get { return 1e-5; } } - protected virtual double RevolutionsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DegreeToAngleUnits() - { - Angle degree = Angle.FromDegrees(1); - AssertEx.EqualTolerance(ArcminutesInOneDegree, degree.Arcminutes, ArcminutesTolerance); - AssertEx.EqualTolerance(ArcsecondsInOneDegree, degree.Arcseconds, ArcsecondsTolerance); - AssertEx.EqualTolerance(CentiradiansInOneDegree, degree.Centiradians, CentiradiansTolerance); - AssertEx.EqualTolerance(DeciradiansInOneDegree, degree.Deciradians, DeciradiansTolerance); - AssertEx.EqualTolerance(DegreesInOneDegree, degree.Degrees, DegreesTolerance); - AssertEx.EqualTolerance(GradiansInOneDegree, degree.Gradians, GradiansTolerance); - AssertEx.EqualTolerance(MicrodegreesInOneDegree, degree.Microdegrees, MicrodegreesTolerance); - AssertEx.EqualTolerance(MicroradiansInOneDegree, degree.Microradians, MicroradiansTolerance); - AssertEx.EqualTolerance(MillidegreesInOneDegree, degree.Millidegrees, MillidegreesTolerance); - AssertEx.EqualTolerance(MilliradiansInOneDegree, degree.Milliradians, MilliradiansTolerance); - AssertEx.EqualTolerance(NanodegreesInOneDegree, degree.Nanodegrees, NanodegreesTolerance); - AssertEx.EqualTolerance(NanoradiansInOneDegree, degree.Nanoradians, NanoradiansTolerance); - AssertEx.EqualTolerance(RadiansInOneDegree, degree.Radians, RadiansTolerance); - AssertEx.EqualTolerance(RevolutionsInOneDegree, degree.Revolutions, RevolutionsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Arcminute).Arcminutes, ArcminutesTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Arcsecond).Arcseconds, ArcsecondsTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Centiradian).Centiradians, CentiradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Deciradian).Deciradians, DeciradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Degree).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Gradian).Gradians, GradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Microdegree).Microdegrees, MicrodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Microradian).Microradians, MicroradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Millidegree).Millidegrees, MillidegreesTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Milliradian).Milliradians, MilliradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Nanodegree).Nanodegrees, NanodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Nanoradian).Nanoradians, NanoradiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Radian).Radians, RadiansTolerance); - AssertEx.EqualTolerance(1, Angle.From(1, AngleUnit.Revolution).Revolutions, RevolutionsTolerance); - } - - [Fact] - public void As() - { - var degree = Angle.FromDegrees(1); - AssertEx.EqualTolerance(ArcminutesInOneDegree, degree.As(AngleUnit.Arcminute), ArcminutesTolerance); - AssertEx.EqualTolerance(ArcsecondsInOneDegree, degree.As(AngleUnit.Arcsecond), ArcsecondsTolerance); - AssertEx.EqualTolerance(CentiradiansInOneDegree, degree.As(AngleUnit.Centiradian), CentiradiansTolerance); - AssertEx.EqualTolerance(DeciradiansInOneDegree, degree.As(AngleUnit.Deciradian), DeciradiansTolerance); - AssertEx.EqualTolerance(DegreesInOneDegree, degree.As(AngleUnit.Degree), DegreesTolerance); - AssertEx.EqualTolerance(GradiansInOneDegree, degree.As(AngleUnit.Gradian), GradiansTolerance); - AssertEx.EqualTolerance(MicrodegreesInOneDegree, degree.As(AngleUnit.Microdegree), MicrodegreesTolerance); - AssertEx.EqualTolerance(MicroradiansInOneDegree, degree.As(AngleUnit.Microradian), MicroradiansTolerance); - AssertEx.EqualTolerance(MillidegreesInOneDegree, degree.As(AngleUnit.Millidegree), MillidegreesTolerance); - AssertEx.EqualTolerance(MilliradiansInOneDegree, degree.As(AngleUnit.Milliradian), MilliradiansTolerance); - AssertEx.EqualTolerance(NanodegreesInOneDegree, degree.As(AngleUnit.Nanodegree), NanodegreesTolerance); - AssertEx.EqualTolerance(NanoradiansInOneDegree, degree.As(AngleUnit.Nanoradian), NanoradiansTolerance); - AssertEx.EqualTolerance(RadiansInOneDegree, degree.As(AngleUnit.Radian), RadiansTolerance); - AssertEx.EqualTolerance(RevolutionsInOneDegree, degree.As(AngleUnit.Revolution), RevolutionsTolerance); - } - - [Fact] - public void ToUnit() - { - var degree = Angle.FromDegrees(1); - - var arcminuteQuantity = degree.ToUnit(AngleUnit.Arcminute); - AssertEx.EqualTolerance(ArcminutesInOneDegree, (double)arcminuteQuantity.Value, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, arcminuteQuantity.Unit); - - var arcsecondQuantity = degree.ToUnit(AngleUnit.Arcsecond); - AssertEx.EqualTolerance(ArcsecondsInOneDegree, (double)arcsecondQuantity.Value, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, arcsecondQuantity.Unit); - - var centiradianQuantity = degree.ToUnit(AngleUnit.Centiradian); - AssertEx.EqualTolerance(CentiradiansInOneDegree, (double)centiradianQuantity.Value, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, centiradianQuantity.Unit); - - var deciradianQuantity = degree.ToUnit(AngleUnit.Deciradian); - AssertEx.EqualTolerance(DeciradiansInOneDegree, (double)deciradianQuantity.Value, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, deciradianQuantity.Unit); - - var degreeQuantity = degree.ToUnit(AngleUnit.Degree); - AssertEx.EqualTolerance(DegreesInOneDegree, (double)degreeQuantity.Value, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, degreeQuantity.Unit); - - var gradianQuantity = degree.ToUnit(AngleUnit.Gradian); - AssertEx.EqualTolerance(GradiansInOneDegree, (double)gradianQuantity.Value, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, gradianQuantity.Unit); - - var microdegreeQuantity = degree.ToUnit(AngleUnit.Microdegree); - AssertEx.EqualTolerance(MicrodegreesInOneDegree, (double)microdegreeQuantity.Value, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, microdegreeQuantity.Unit); - - var microradianQuantity = degree.ToUnit(AngleUnit.Microradian); - AssertEx.EqualTolerance(MicroradiansInOneDegree, (double)microradianQuantity.Value, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, microradianQuantity.Unit); - - var millidegreeQuantity = degree.ToUnit(AngleUnit.Millidegree); - AssertEx.EqualTolerance(MillidegreesInOneDegree, (double)millidegreeQuantity.Value, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, millidegreeQuantity.Unit); - - var milliradianQuantity = degree.ToUnit(AngleUnit.Milliradian); - AssertEx.EqualTolerance(MilliradiansInOneDegree, (double)milliradianQuantity.Value, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, milliradianQuantity.Unit); - - var nanodegreeQuantity = degree.ToUnit(AngleUnit.Nanodegree); - AssertEx.EqualTolerance(NanodegreesInOneDegree, (double)nanodegreeQuantity.Value, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, nanodegreeQuantity.Unit); - - var nanoradianQuantity = degree.ToUnit(AngleUnit.Nanoradian); - AssertEx.EqualTolerance(NanoradiansInOneDegree, (double)nanoradianQuantity.Value, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, nanoradianQuantity.Unit); - - var radianQuantity = degree.ToUnit(AngleUnit.Radian); - AssertEx.EqualTolerance(RadiansInOneDegree, (double)radianQuantity.Value, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, radianQuantity.Unit); - - var revolutionQuantity = degree.ToUnit(AngleUnit.Revolution); - AssertEx.EqualTolerance(RevolutionsInOneDegree, (double)revolutionQuantity.Value, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, revolutionQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Angle degree = Angle.FromDegrees(1); - AssertEx.EqualTolerance(1, Angle.FromArcminutes(degree.Arcminutes).Degrees, ArcminutesTolerance); - AssertEx.EqualTolerance(1, Angle.FromArcseconds(degree.Arcseconds).Degrees, ArcsecondsTolerance); - AssertEx.EqualTolerance(1, Angle.FromCentiradians(degree.Centiradians).Degrees, CentiradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromDeciradians(degree.Deciradians).Degrees, DeciradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromDegrees(degree.Degrees).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromGradians(degree.Gradians).Degrees, GradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromMicrodegrees(degree.Microdegrees).Degrees, MicrodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromMicroradians(degree.Microradians).Degrees, MicroradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromMillidegrees(degree.Millidegrees).Degrees, MillidegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromMilliradians(degree.Milliradians).Degrees, MilliradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromNanodegrees(degree.Nanodegrees).Degrees, NanodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromNanoradians(degree.Nanoradians).Degrees, NanoradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromRadians(degree.Radians).Degrees, RadiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromRevolutions(degree.Revolutions).Degrees, RevolutionsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Angle v = Angle.FromDegrees(1); - AssertEx.EqualTolerance(-1, -v.Degrees, DegreesTolerance); - AssertEx.EqualTolerance(2, (Angle.FromDegrees(3)-v).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(2, (v + v).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(10, (v*10).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(10, (10*v).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(2, (Angle.FromDegrees(10)/5).Degrees, DegreesTolerance); - AssertEx.EqualTolerance(2, Angle.FromDegrees(10)/Angle.FromDegrees(5), DegreesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Angle oneDegree = Angle.FromDegrees(1); - Angle twoDegrees = Angle.FromDegrees(2); - - Assert.True(oneDegree < twoDegrees); - Assert.True(oneDegree <= twoDegrees); - Assert.True(twoDegrees > oneDegree); - Assert.True(twoDegrees >= oneDegree); - - Assert.False(oneDegree > twoDegrees); - Assert.False(oneDegree >= twoDegrees); - Assert.False(twoDegrees < oneDegree); - Assert.False(twoDegrees <= oneDegree); - } - - [Fact] - public void CompareToIsImplemented() - { - Angle degree = Angle.FromDegrees(1); - Assert.Equal(0, degree.CompareTo(degree)); - Assert.True(degree.CompareTo(Angle.Zero) > 0); - Assert.True(Angle.Zero.CompareTo(degree) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Angle degree = Angle.FromDegrees(1); - Assert.Throws(() => degree.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Angle degree = Angle.FromDegrees(1); - Assert.Throws(() => degree.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Angle a = Angle.FromDegrees(1); - Angle b = Angle.FromDegrees(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Angle v = Angle.FromDegrees(1); - Assert.True(v.Equals(Angle.FromDegrees(1), Angle.FromDegrees(DegreesTolerance))); - Assert.False(v.Equals(Angle.Zero, Angle.FromDegrees(DegreesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Angle degree = Angle.FromDegrees(1); - Assert.False(degree.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Angle degree = Angle.FromDegrees(1); - Assert.False(degree.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AngleUnit.Undefined, Angle.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ApparentEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ApparentEnergyTestsBase.g.cs deleted file mode 100644 index 7515f60b10..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ApparentEnergyTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ApparentEnergy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ApparentEnergyTestsBase - { - protected abstract double KilovoltampereHoursInOneVoltampereHour { get; } - protected abstract double MegavoltampereHoursInOneVoltampereHour { get; } - protected abstract double VoltampereHoursInOneVoltampereHour { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltampereHoursTolerance { get { return 1e-5; } } - protected virtual double MegavoltampereHoursTolerance { get { return 1e-5; } } - protected virtual double VoltampereHoursTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltampereHourToApparentEnergyUnits() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(KilovoltampereHoursInOneVoltampereHour, voltamperehour.KilovoltampereHours, KilovoltampereHoursTolerance); - AssertEx.EqualTolerance(MegavoltampereHoursInOneVoltampereHour, voltamperehour.MegavoltampereHours, MegavoltampereHoursTolerance); - AssertEx.EqualTolerance(VoltampereHoursInOneVoltampereHour, voltamperehour.VoltampereHours, VoltampereHoursTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ApparentEnergy.From(1, ApparentEnergyUnit.KilovoltampereHour).KilovoltampereHours, KilovoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ApparentEnergy.From(1, ApparentEnergyUnit.MegavoltampereHour).MegavoltampereHours, MegavoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ApparentEnergy.From(1, ApparentEnergyUnit.VoltampereHour).VoltampereHours, VoltampereHoursTolerance); - } - - [Fact] - public void As() - { - var voltamperehour = ApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(KilovoltampereHoursInOneVoltampereHour, voltamperehour.As(ApparentEnergyUnit.KilovoltampereHour), KilovoltampereHoursTolerance); - AssertEx.EqualTolerance(MegavoltampereHoursInOneVoltampereHour, voltamperehour.As(ApparentEnergyUnit.MegavoltampereHour), MegavoltampereHoursTolerance); - AssertEx.EqualTolerance(VoltampereHoursInOneVoltampereHour, voltamperehour.As(ApparentEnergyUnit.VoltampereHour), VoltampereHoursTolerance); - } - - [Fact] - public void ToUnit() - { - var voltamperehour = ApparentEnergy.FromVoltampereHours(1); - - var kilovoltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.KilovoltampereHour); - AssertEx.EqualTolerance(KilovoltampereHoursInOneVoltampereHour, (double)kilovoltamperehourQuantity.Value, KilovoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.KilovoltampereHour, kilovoltamperehourQuantity.Unit); - - var megavoltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.MegavoltampereHour); - AssertEx.EqualTolerance(MegavoltampereHoursInOneVoltampereHour, (double)megavoltamperehourQuantity.Value, MegavoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.MegavoltampereHour, megavoltamperehourQuantity.Unit); - - var voltamperehourQuantity = voltamperehour.ToUnit(ApparentEnergyUnit.VoltampereHour); - AssertEx.EqualTolerance(VoltampereHoursInOneVoltampereHour, (double)voltamperehourQuantity.Value, VoltampereHoursTolerance); - Assert.Equal(ApparentEnergyUnit.VoltampereHour, voltamperehourQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(1, ApparentEnergy.FromKilovoltampereHours(voltamperehour.KilovoltampereHours).VoltampereHours, KilovoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ApparentEnergy.FromMegavoltampereHours(voltamperehour.MegavoltampereHours).VoltampereHours, MegavoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ApparentEnergy.FromVoltampereHours(voltamperehour.VoltampereHours).VoltampereHours, VoltampereHoursTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ApparentEnergy v = ApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(-1, -v.VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (ApparentEnergy.FromVoltampereHours(3)-v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (ApparentEnergy.FromVoltampereHours(10)/5).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, ApparentEnergy.FromVoltampereHours(10)/ApparentEnergy.FromVoltampereHours(5), VoltampereHoursTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ApparentEnergy oneVoltampereHour = ApparentEnergy.FromVoltampereHours(1); - ApparentEnergy twoVoltampereHours = ApparentEnergy.FromVoltampereHours(2); - - Assert.True(oneVoltampereHour < twoVoltampereHours); - Assert.True(oneVoltampereHour <= twoVoltampereHours); - Assert.True(twoVoltampereHours > oneVoltampereHour); - Assert.True(twoVoltampereHours >= oneVoltampereHour); - - Assert.False(oneVoltampereHour > twoVoltampereHours); - Assert.False(oneVoltampereHour >= twoVoltampereHours); - Assert.False(twoVoltampereHours < oneVoltampereHour); - Assert.False(twoVoltampereHours <= oneVoltampereHour); - } - - [Fact] - public void CompareToIsImplemented() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - Assert.Equal(0, voltamperehour.CompareTo(voltamperehour)); - Assert.True(voltamperehour.CompareTo(ApparentEnergy.Zero) > 0); - Assert.True(ApparentEnergy.Zero.CompareTo(voltamperehour) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - Assert.Throws(() => voltamperehour.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - Assert.Throws(() => voltamperehour.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ApparentEnergy a = ApparentEnergy.FromVoltampereHours(1); - ApparentEnergy b = ApparentEnergy.FromVoltampereHours(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ApparentEnergy v = ApparentEnergy.FromVoltampereHours(1); - Assert.True(v.Equals(ApparentEnergy.FromVoltampereHours(1), ApparentEnergy.FromVoltampereHours(VoltampereHoursTolerance))); - Assert.False(v.Equals(ApparentEnergy.Zero, ApparentEnergy.FromVoltampereHours(VoltampereHoursTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - Assert.False(voltamperehour.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ApparentEnergy voltamperehour = ApparentEnergy.FromVoltampereHours(1); - Assert.False(voltamperehour.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ApparentEnergyUnit.Undefined, ApparentEnergy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ApparentPowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ApparentPowerTestsBase.g.cs deleted file mode 100644 index 198401e9cd..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ApparentPowerTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ApparentPower. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ApparentPowerTestsBase - { - protected abstract double GigavoltamperesInOneVoltampere { get; } - protected abstract double KilovoltamperesInOneVoltampere { get; } - protected abstract double MegavoltamperesInOneVoltampere { get; } - protected abstract double VoltamperesInOneVoltampere { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigavoltamperesTolerance { get { return 1e-5; } } - protected virtual double KilovoltamperesTolerance { get { return 1e-5; } } - protected virtual double MegavoltamperesTolerance { get { return 1e-5; } } - protected virtual double VoltamperesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltampereToApparentPowerUnits() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(GigavoltamperesInOneVoltampere, voltampere.Gigavoltamperes, GigavoltamperesTolerance); - AssertEx.EqualTolerance(KilovoltamperesInOneVoltampere, voltampere.Kilovoltamperes, KilovoltamperesTolerance); - AssertEx.EqualTolerance(MegavoltamperesInOneVoltampere, voltampere.Megavoltamperes, MegavoltamperesTolerance); - AssertEx.EqualTolerance(VoltamperesInOneVoltampere, voltampere.Voltamperes, VoltamperesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ApparentPower.From(1, ApparentPowerUnit.Gigavoltampere).Gigavoltamperes, GigavoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.From(1, ApparentPowerUnit.Kilovoltampere).Kilovoltamperes, KilovoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.From(1, ApparentPowerUnit.Megavoltampere).Megavoltamperes, MegavoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.From(1, ApparentPowerUnit.Voltampere).Voltamperes, VoltamperesTolerance); - } - - [Fact] - public void As() - { - var voltampere = ApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(GigavoltamperesInOneVoltampere, voltampere.As(ApparentPowerUnit.Gigavoltampere), GigavoltamperesTolerance); - AssertEx.EqualTolerance(KilovoltamperesInOneVoltampere, voltampere.As(ApparentPowerUnit.Kilovoltampere), KilovoltamperesTolerance); - AssertEx.EqualTolerance(MegavoltamperesInOneVoltampere, voltampere.As(ApparentPowerUnit.Megavoltampere), MegavoltamperesTolerance); - AssertEx.EqualTolerance(VoltamperesInOneVoltampere, voltampere.As(ApparentPowerUnit.Voltampere), VoltamperesTolerance); - } - - [Fact] - public void ToUnit() - { - var voltampere = ApparentPower.FromVoltamperes(1); - - var gigavoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Gigavoltampere); - AssertEx.EqualTolerance(GigavoltamperesInOneVoltampere, (double)gigavoltampereQuantity.Value, GigavoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Gigavoltampere, gigavoltampereQuantity.Unit); - - var kilovoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Kilovoltampere); - AssertEx.EqualTolerance(KilovoltamperesInOneVoltampere, (double)kilovoltampereQuantity.Value, KilovoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Kilovoltampere, kilovoltampereQuantity.Unit); - - var megavoltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Megavoltampere); - AssertEx.EqualTolerance(MegavoltamperesInOneVoltampere, (double)megavoltampereQuantity.Value, MegavoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Megavoltampere, megavoltampereQuantity.Unit); - - var voltampereQuantity = voltampere.ToUnit(ApparentPowerUnit.Voltampere); - AssertEx.EqualTolerance(VoltamperesInOneVoltampere, (double)voltampereQuantity.Value, VoltamperesTolerance); - Assert.Equal(ApparentPowerUnit.Voltampere, voltampereQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(1, ApparentPower.FromGigavoltamperes(voltampere.Gigavoltamperes).Voltamperes, GigavoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.FromKilovoltamperes(voltampere.Kilovoltamperes).Voltamperes, KilovoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.FromMegavoltamperes(voltampere.Megavoltamperes).Voltamperes, MegavoltamperesTolerance); - AssertEx.EqualTolerance(1, ApparentPower.FromVoltamperes(voltampere.Voltamperes).Voltamperes, VoltamperesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ApparentPower v = ApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(-1, -v.Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (ApparentPower.FromVoltamperes(3)-v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (v + v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(10, (v*10).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(10, (10*v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (ApparentPower.FromVoltamperes(10)/5).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, ApparentPower.FromVoltamperes(10)/ApparentPower.FromVoltamperes(5), VoltamperesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ApparentPower oneVoltampere = ApparentPower.FromVoltamperes(1); - ApparentPower twoVoltamperes = ApparentPower.FromVoltamperes(2); - - Assert.True(oneVoltampere < twoVoltamperes); - Assert.True(oneVoltampere <= twoVoltamperes); - Assert.True(twoVoltamperes > oneVoltampere); - Assert.True(twoVoltamperes >= oneVoltampere); - - Assert.False(oneVoltampere > twoVoltamperes); - Assert.False(oneVoltampere >= twoVoltamperes); - Assert.False(twoVoltamperes < oneVoltampere); - Assert.False(twoVoltamperes <= oneVoltampere); - } - - [Fact] - public void CompareToIsImplemented() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - Assert.Equal(0, voltampere.CompareTo(voltampere)); - Assert.True(voltampere.CompareTo(ApparentPower.Zero) > 0); - Assert.True(ApparentPower.Zero.CompareTo(voltampere) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - Assert.Throws(() => voltampere.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - Assert.Throws(() => voltampere.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ApparentPower a = ApparentPower.FromVoltamperes(1); - ApparentPower b = ApparentPower.FromVoltamperes(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ApparentPower v = ApparentPower.FromVoltamperes(1); - Assert.True(v.Equals(ApparentPower.FromVoltamperes(1), ApparentPower.FromVoltamperes(VoltamperesTolerance))); - Assert.False(v.Equals(ApparentPower.Zero, ApparentPower.FromVoltamperes(VoltamperesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - Assert.False(voltampere.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ApparentPower voltampere = ApparentPower.FromVoltamperes(1); - Assert.False(voltampere.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ApparentPowerUnit.Undefined, ApparentPower.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AreaDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AreaDensityTestsBase.g.cs deleted file mode 100644 index bb580bc641..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AreaDensityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of AreaDensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AreaDensityTestsBase - { - protected abstract double KilogramsPerSquareMeterInOneKilogramPerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramsPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerSquareMeterToAreaDensityUnits() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(KilogramsPerSquareMeterInOneKilogramPerSquareMeter, kilogrampersquaremeter.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, AreaDensity.From(1, AreaDensityUnit.KilogramPerSquareMeter).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(KilogramsPerSquareMeterInOneKilogramPerSquareMeter, kilogrampersquaremeter.As(AreaDensityUnit.KilogramPerSquareMeter), KilogramsPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - - var kilogrampersquaremeterQuantity = kilogrampersquaremeter.ToUnit(AreaDensityUnit.KilogramPerSquareMeter); - AssertEx.EqualTolerance(KilogramsPerSquareMeterInOneKilogramPerSquareMeter, (double)kilogrampersquaremeterQuantity.Value, KilogramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, kilogrampersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(1, AreaDensity.FromKilogramsPerSquareMeter(kilogrampersquaremeter.KilogramsPerSquareMeter).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - AreaDensity v = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (AreaDensity.FromKilogramsPerSquareMeter(3)-v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (AreaDensity.FromKilogramsPerSquareMeter(10)/5).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, AreaDensity.FromKilogramsPerSquareMeter(10)/AreaDensity.FromKilogramsPerSquareMeter(5), KilogramsPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - AreaDensity oneKilogramPerSquareMeter = AreaDensity.FromKilogramsPerSquareMeter(1); - AreaDensity twoKilogramsPerSquareMeter = AreaDensity.FromKilogramsPerSquareMeter(2); - - Assert.True(oneKilogramPerSquareMeter < twoKilogramsPerSquareMeter); - Assert.True(oneKilogramPerSquareMeter <= twoKilogramsPerSquareMeter); - Assert.True(twoKilogramsPerSquareMeter > oneKilogramPerSquareMeter); - Assert.True(twoKilogramsPerSquareMeter >= oneKilogramPerSquareMeter); - - Assert.False(oneKilogramPerSquareMeter > twoKilogramsPerSquareMeter); - Assert.False(oneKilogramPerSquareMeter >= twoKilogramsPerSquareMeter); - Assert.False(twoKilogramsPerSquareMeter < oneKilogramPerSquareMeter); - Assert.False(twoKilogramsPerSquareMeter <= oneKilogramPerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.Equal(0, kilogrampersquaremeter.CompareTo(kilogrampersquaremeter)); - Assert.True(kilogrampersquaremeter.CompareTo(AreaDensity.Zero) > 0); - Assert.True(AreaDensity.Zero.CompareTo(kilogrampersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.Throws(() => kilogrampersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.Throws(() => kilogrampersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - AreaDensity a = AreaDensity.FromKilogramsPerSquareMeter(1); - AreaDensity b = AreaDensity.FromKilogramsPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - AreaDensity v = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.True(v.Equals(AreaDensity.FromKilogramsPerSquareMeter(1), AreaDensity.FromKilogramsPerSquareMeter(KilogramsPerSquareMeterTolerance))); - Assert.False(v.Equals(AreaDensity.Zero, AreaDensity.FromKilogramsPerSquareMeter(KilogramsPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.False(kilogrampersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.False(kilogrampersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaDensityUnit.Undefined, AreaDensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AreaMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AreaMomentOfInertiaTestsBase.g.cs deleted file mode 100644 index 0811084f53..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AreaMomentOfInertiaTestsBase.g.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of AreaMomentOfInertia. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AreaMomentOfInertiaTestsBase - { - protected abstract double CentimetersToTheFourthInOneMeterToTheFourth { get; } - protected abstract double DecimetersToTheFourthInOneMeterToTheFourth { get; } - protected abstract double FeetToTheFourthInOneMeterToTheFourth { get; } - protected abstract double InchesToTheFourthInOneMeterToTheFourth { get; } - protected abstract double MetersToTheFourthInOneMeterToTheFourth { get; } - protected abstract double MillimetersToTheFourthInOneMeterToTheFourth { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double DecimetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double FeetToTheFourthTolerance { get { return 1e-5; } } - protected virtual double InchesToTheFourthTolerance { get { return 1e-5; } } - protected virtual double MetersToTheFourthTolerance { get { return 1e-5; } } - protected virtual double MillimetersToTheFourthTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void MeterToTheFourthToAreaMomentOfInertiaUnits() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(CentimetersToTheFourthInOneMeterToTheFourth, metertothefourth.CentimetersToTheFourth, CentimetersToTheFourthTolerance); - AssertEx.EqualTolerance(DecimetersToTheFourthInOneMeterToTheFourth, metertothefourth.DecimetersToTheFourth, DecimetersToTheFourthTolerance); - AssertEx.EqualTolerance(FeetToTheFourthInOneMeterToTheFourth, metertothefourth.FeetToTheFourth, FeetToTheFourthTolerance); - AssertEx.EqualTolerance(InchesToTheFourthInOneMeterToTheFourth, metertothefourth.InchesToTheFourth, InchesToTheFourthTolerance); - AssertEx.EqualTolerance(MetersToTheFourthInOneMeterToTheFourth, metertothefourth.MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(MillimetersToTheFourthInOneMeterToTheFourth, metertothefourth.MillimetersToTheFourth, MillimetersToTheFourthTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.CentimeterToTheFourth).CentimetersToTheFourth, CentimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.DecimeterToTheFourth).DecimetersToTheFourth, DecimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.FootToTheFourth).FeetToTheFourth, FeetToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.InchToTheFourth).InchesToTheFourth, InchesToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.MeterToTheFourth).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.MillimeterToTheFourth).MillimetersToTheFourth, MillimetersToTheFourthTolerance); - } - - [Fact] - public void As() - { - var metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(CentimetersToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.CentimeterToTheFourth), CentimetersToTheFourthTolerance); - AssertEx.EqualTolerance(DecimetersToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.DecimeterToTheFourth), DecimetersToTheFourthTolerance); - AssertEx.EqualTolerance(FeetToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.FootToTheFourth), FeetToTheFourthTolerance); - AssertEx.EqualTolerance(InchesToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.InchToTheFourth), InchesToTheFourthTolerance); - AssertEx.EqualTolerance(MetersToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.MeterToTheFourth), MetersToTheFourthTolerance); - AssertEx.EqualTolerance(MillimetersToTheFourthInOneMeterToTheFourth, metertothefourth.As(AreaMomentOfInertiaUnit.MillimeterToTheFourth), MillimetersToTheFourthTolerance); - } - - [Fact] - public void ToUnit() - { - var metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - - var centimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.CentimeterToTheFourth); - AssertEx.EqualTolerance(CentimetersToTheFourthInOneMeterToTheFourth, (double)centimetertothefourthQuantity.Value, CentimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.CentimeterToTheFourth, centimetertothefourthQuantity.Unit); - - var decimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.DecimeterToTheFourth); - AssertEx.EqualTolerance(DecimetersToTheFourthInOneMeterToTheFourth, (double)decimetertothefourthQuantity.Value, DecimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.DecimeterToTheFourth, decimetertothefourthQuantity.Unit); - - var foottothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.FootToTheFourth); - AssertEx.EqualTolerance(FeetToTheFourthInOneMeterToTheFourth, (double)foottothefourthQuantity.Value, FeetToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.FootToTheFourth, foottothefourthQuantity.Unit); - - var inchtothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.InchToTheFourth); - AssertEx.EqualTolerance(InchesToTheFourthInOneMeterToTheFourth, (double)inchtothefourthQuantity.Value, InchesToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.InchToTheFourth, inchtothefourthQuantity.Unit); - - var metertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth); - AssertEx.EqualTolerance(MetersToTheFourthInOneMeterToTheFourth, (double)metertothefourthQuantity.Value, MetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, metertothefourthQuantity.Unit); - - var millimetertothefourthQuantity = metertothefourth.ToUnit(AreaMomentOfInertiaUnit.MillimeterToTheFourth); - AssertEx.EqualTolerance(MillimetersToTheFourthInOneMeterToTheFourth, (double)millimetertothefourthQuantity.Value, MillimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MillimeterToTheFourth, millimetertothefourthQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromCentimetersToTheFourth(metertothefourth.CentimetersToTheFourth).MetersToTheFourth, CentimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromDecimetersToTheFourth(metertothefourth.DecimetersToTheFourth).MetersToTheFourth, DecimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromFeetToTheFourth(metertothefourth.FeetToTheFourth).MetersToTheFourth, FeetToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromInchesToTheFourth(metertothefourth.InchesToTheFourth).MetersToTheFourth, InchesToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromMetersToTheFourth(metertothefourth.MetersToTheFourth).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromMillimetersToTheFourth(metertothefourth.MillimetersToTheFourth).MetersToTheFourth, MillimetersToTheFourthTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - AreaMomentOfInertia v = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(-1, -v.MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (AreaMomentOfInertia.FromMetersToTheFourth(3)-v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (AreaMomentOfInertia.FromMetersToTheFourth(10)/5).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, AreaMomentOfInertia.FromMetersToTheFourth(10)/AreaMomentOfInertia.FromMetersToTheFourth(5), MetersToTheFourthTolerance); - } - - [Fact] - public void ComparisonOperators() - { - AreaMomentOfInertia oneMeterToTheFourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - AreaMomentOfInertia twoMetersToTheFourth = AreaMomentOfInertia.FromMetersToTheFourth(2); - - Assert.True(oneMeterToTheFourth < twoMetersToTheFourth); - Assert.True(oneMeterToTheFourth <= twoMetersToTheFourth); - Assert.True(twoMetersToTheFourth > oneMeterToTheFourth); - Assert.True(twoMetersToTheFourth >= oneMeterToTheFourth); - - Assert.False(oneMeterToTheFourth > twoMetersToTheFourth); - Assert.False(oneMeterToTheFourth >= twoMetersToTheFourth); - Assert.False(twoMetersToTheFourth < oneMeterToTheFourth); - Assert.False(twoMetersToTheFourth <= oneMeterToTheFourth); - } - - [Fact] - public void CompareToIsImplemented() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.Equal(0, metertothefourth.CompareTo(metertothefourth)); - Assert.True(metertothefourth.CompareTo(AreaMomentOfInertia.Zero) > 0); - Assert.True(AreaMomentOfInertia.Zero.CompareTo(metertothefourth) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.Throws(() => metertothefourth.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.Throws(() => metertothefourth.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - AreaMomentOfInertia a = AreaMomentOfInertia.FromMetersToTheFourth(1); - AreaMomentOfInertia b = AreaMomentOfInertia.FromMetersToTheFourth(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - AreaMomentOfInertia v = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.True(v.Equals(AreaMomentOfInertia.FromMetersToTheFourth(1), AreaMomentOfInertia.FromMetersToTheFourth(MetersToTheFourthTolerance))); - Assert.False(v.Equals(AreaMomentOfInertia.Zero, AreaMomentOfInertia.FromMetersToTheFourth(MetersToTheFourthTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.False(metertothefourth.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.False(metertothefourth.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaMomentOfInertiaUnit.Undefined, AreaMomentOfInertia.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/AreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/AreaTestsBase.g.cs deleted file mode 100644 index bc77c9e71f..0000000000 --- a/UnitsNet.Tests/GeneratedCode/AreaTestsBase.g.cs +++ /dev/null @@ -1,317 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Area. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class AreaTestsBase - { - protected abstract double AcresInOneSquareMeter { get; } - protected abstract double HectaresInOneSquareMeter { get; } - protected abstract double SquareCentimetersInOneSquareMeter { get; } - protected abstract double SquareDecimetersInOneSquareMeter { get; } - protected abstract double SquareFeetInOneSquareMeter { get; } - protected abstract double SquareInchesInOneSquareMeter { get; } - protected abstract double SquareKilometersInOneSquareMeter { get; } - protected abstract double SquareMetersInOneSquareMeter { get; } - protected abstract double SquareMicrometersInOneSquareMeter { get; } - protected abstract double SquareMilesInOneSquareMeter { get; } - protected abstract double SquareMillimetersInOneSquareMeter { get; } - protected abstract double SquareYardsInOneSquareMeter { get; } - protected abstract double UsSurveySquareFeetInOneSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AcresTolerance { get { return 1e-5; } } - protected virtual double HectaresTolerance { get { return 1e-5; } } - protected virtual double SquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double SquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double SquareFeetTolerance { get { return 1e-5; } } - protected virtual double SquareInchesTolerance { get { return 1e-5; } } - protected virtual double SquareKilometersTolerance { get { return 1e-5; } } - protected virtual double SquareMetersTolerance { get { return 1e-5; } } - protected virtual double SquareMicrometersTolerance { get { return 1e-5; } } - protected virtual double SquareMilesTolerance { get { return 1e-5; } } - protected virtual double SquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double SquareYardsTolerance { get { return 1e-5; } } - protected virtual double UsSurveySquareFeetTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SquareMeterToAreaUnits() - { - Area squaremeter = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(AcresInOneSquareMeter, squaremeter.Acres, AcresTolerance); - AssertEx.EqualTolerance(HectaresInOneSquareMeter, squaremeter.Hectares, HectaresTolerance); - AssertEx.EqualTolerance(SquareCentimetersInOneSquareMeter, squaremeter.SquareCentimeters, SquareCentimetersTolerance); - AssertEx.EqualTolerance(SquareDecimetersInOneSquareMeter, squaremeter.SquareDecimeters, SquareDecimetersTolerance); - AssertEx.EqualTolerance(SquareFeetInOneSquareMeter, squaremeter.SquareFeet, SquareFeetTolerance); - AssertEx.EqualTolerance(SquareInchesInOneSquareMeter, squaremeter.SquareInches, SquareInchesTolerance); - AssertEx.EqualTolerance(SquareKilometersInOneSquareMeter, squaremeter.SquareKilometers, SquareKilometersTolerance); - AssertEx.EqualTolerance(SquareMetersInOneSquareMeter, squaremeter.SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(SquareMicrometersInOneSquareMeter, squaremeter.SquareMicrometers, SquareMicrometersTolerance); - AssertEx.EqualTolerance(SquareMilesInOneSquareMeter, squaremeter.SquareMiles, SquareMilesTolerance); - AssertEx.EqualTolerance(SquareMillimetersInOneSquareMeter, squaremeter.SquareMillimeters, SquareMillimetersTolerance); - AssertEx.EqualTolerance(SquareYardsInOneSquareMeter, squaremeter.SquareYards, SquareYardsTolerance); - AssertEx.EqualTolerance(UsSurveySquareFeetInOneSquareMeter, squaremeter.UsSurveySquareFeet, UsSurveySquareFeetTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.Acre).Acres, AcresTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.Hectare).Hectares, HectaresTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareCentimeter).SquareCentimeters, SquareCentimetersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareDecimeter).SquareDecimeters, SquareDecimetersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareFoot).SquareFeet, SquareFeetTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareInch).SquareInches, SquareInchesTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareKilometer).SquareKilometers, SquareKilometersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareMeter).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareMicrometer).SquareMicrometers, SquareMicrometersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareMile).SquareMiles, SquareMilesTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareMillimeter).SquareMillimeters, SquareMillimetersTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.SquareYard).SquareYards, SquareYardsTolerance); - AssertEx.EqualTolerance(1, Area.From(1, AreaUnit.UsSurveySquareFoot).UsSurveySquareFeet, UsSurveySquareFeetTolerance); - } - - [Fact] - public void As() - { - var squaremeter = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(AcresInOneSquareMeter, squaremeter.As(AreaUnit.Acre), AcresTolerance); - AssertEx.EqualTolerance(HectaresInOneSquareMeter, squaremeter.As(AreaUnit.Hectare), HectaresTolerance); - AssertEx.EqualTolerance(SquareCentimetersInOneSquareMeter, squaremeter.As(AreaUnit.SquareCentimeter), SquareCentimetersTolerance); - AssertEx.EqualTolerance(SquareDecimetersInOneSquareMeter, squaremeter.As(AreaUnit.SquareDecimeter), SquareDecimetersTolerance); - AssertEx.EqualTolerance(SquareFeetInOneSquareMeter, squaremeter.As(AreaUnit.SquareFoot), SquareFeetTolerance); - AssertEx.EqualTolerance(SquareInchesInOneSquareMeter, squaremeter.As(AreaUnit.SquareInch), SquareInchesTolerance); - AssertEx.EqualTolerance(SquareKilometersInOneSquareMeter, squaremeter.As(AreaUnit.SquareKilometer), SquareKilometersTolerance); - AssertEx.EqualTolerance(SquareMetersInOneSquareMeter, squaremeter.As(AreaUnit.SquareMeter), SquareMetersTolerance); - AssertEx.EqualTolerance(SquareMicrometersInOneSquareMeter, squaremeter.As(AreaUnit.SquareMicrometer), SquareMicrometersTolerance); - AssertEx.EqualTolerance(SquareMilesInOneSquareMeter, squaremeter.As(AreaUnit.SquareMile), SquareMilesTolerance); - AssertEx.EqualTolerance(SquareMillimetersInOneSquareMeter, squaremeter.As(AreaUnit.SquareMillimeter), SquareMillimetersTolerance); - AssertEx.EqualTolerance(SquareYardsInOneSquareMeter, squaremeter.As(AreaUnit.SquareYard), SquareYardsTolerance); - AssertEx.EqualTolerance(UsSurveySquareFeetInOneSquareMeter, squaremeter.As(AreaUnit.UsSurveySquareFoot), UsSurveySquareFeetTolerance); - } - - [Fact] - public void ToUnit() - { - var squaremeter = Area.FromSquareMeters(1); - - var acreQuantity = squaremeter.ToUnit(AreaUnit.Acre); - AssertEx.EqualTolerance(AcresInOneSquareMeter, (double)acreQuantity.Value, AcresTolerance); - Assert.Equal(AreaUnit.Acre, acreQuantity.Unit); - - var hectareQuantity = squaremeter.ToUnit(AreaUnit.Hectare); - AssertEx.EqualTolerance(HectaresInOneSquareMeter, (double)hectareQuantity.Value, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, hectareQuantity.Unit); - - var squarecentimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareCentimeter); - AssertEx.EqualTolerance(SquareCentimetersInOneSquareMeter, (double)squarecentimeterQuantity.Value, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, squarecentimeterQuantity.Unit); - - var squaredecimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareDecimeter); - AssertEx.EqualTolerance(SquareDecimetersInOneSquareMeter, (double)squaredecimeterQuantity.Value, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, squaredecimeterQuantity.Unit); - - var squarefootQuantity = squaremeter.ToUnit(AreaUnit.SquareFoot); - AssertEx.EqualTolerance(SquareFeetInOneSquareMeter, (double)squarefootQuantity.Value, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, squarefootQuantity.Unit); - - var squareinchQuantity = squaremeter.ToUnit(AreaUnit.SquareInch); - AssertEx.EqualTolerance(SquareInchesInOneSquareMeter, (double)squareinchQuantity.Value, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, squareinchQuantity.Unit); - - var squarekilometerQuantity = squaremeter.ToUnit(AreaUnit.SquareKilometer); - AssertEx.EqualTolerance(SquareKilometersInOneSquareMeter, (double)squarekilometerQuantity.Value, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, squarekilometerQuantity.Unit); - - var squaremeterQuantity = squaremeter.ToUnit(AreaUnit.SquareMeter); - AssertEx.EqualTolerance(SquareMetersInOneSquareMeter, (double)squaremeterQuantity.Value, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, squaremeterQuantity.Unit); - - var squaremicrometerQuantity = squaremeter.ToUnit(AreaUnit.SquareMicrometer); - AssertEx.EqualTolerance(SquareMicrometersInOneSquareMeter, (double)squaremicrometerQuantity.Value, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, squaremicrometerQuantity.Unit); - - var squaremileQuantity = squaremeter.ToUnit(AreaUnit.SquareMile); - AssertEx.EqualTolerance(SquareMilesInOneSquareMeter, (double)squaremileQuantity.Value, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, squaremileQuantity.Unit); - - var squaremillimeterQuantity = squaremeter.ToUnit(AreaUnit.SquareMillimeter); - AssertEx.EqualTolerance(SquareMillimetersInOneSquareMeter, (double)squaremillimeterQuantity.Value, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, squaremillimeterQuantity.Unit); - - var squareyardQuantity = squaremeter.ToUnit(AreaUnit.SquareYard); - AssertEx.EqualTolerance(SquareYardsInOneSquareMeter, (double)squareyardQuantity.Value, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, squareyardQuantity.Unit); - - var ussurveysquarefootQuantity = squaremeter.ToUnit(AreaUnit.UsSurveySquareFoot); - AssertEx.EqualTolerance(UsSurveySquareFeetInOneSquareMeter, (double)ussurveysquarefootQuantity.Value, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, ussurveysquarefootQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Area squaremeter = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(1, Area.FromAcres(squaremeter.Acres).SquareMeters, AcresTolerance); - AssertEx.EqualTolerance(1, Area.FromHectares(squaremeter.Hectares).SquareMeters, HectaresTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareCentimeters(squaremeter.SquareCentimeters).SquareMeters, SquareCentimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareDecimeters(squaremeter.SquareDecimeters).SquareMeters, SquareDecimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareFeet(squaremeter.SquareFeet).SquareMeters, SquareFeetTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareInches(squaremeter.SquareInches).SquareMeters, SquareInchesTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareKilometers(squaremeter.SquareKilometers).SquareMeters, SquareKilometersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMeters(squaremeter.SquareMeters).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMicrometers(squaremeter.SquareMicrometers).SquareMeters, SquareMicrometersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMiles(squaremeter.SquareMiles).SquareMeters, SquareMilesTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMillimeters(squaremeter.SquareMillimeters).SquareMeters, SquareMillimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareYards(squaremeter.SquareYards).SquareMeters, SquareYardsTolerance); - AssertEx.EqualTolerance(1, Area.FromUsSurveySquareFeet(squaremeter.UsSurveySquareFeet).SquareMeters, UsSurveySquareFeetTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Area v = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (Area.FromSquareMeters(3)-v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (Area.FromSquareMeters(10)/5).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, Area.FromSquareMeters(10)/Area.FromSquareMeters(5), SquareMetersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Area oneSquareMeter = Area.FromSquareMeters(1); - Area twoSquareMeters = Area.FromSquareMeters(2); - - Assert.True(oneSquareMeter < twoSquareMeters); - Assert.True(oneSquareMeter <= twoSquareMeters); - Assert.True(twoSquareMeters > oneSquareMeter); - Assert.True(twoSquareMeters >= oneSquareMeter); - - Assert.False(oneSquareMeter > twoSquareMeters); - Assert.False(oneSquareMeter >= twoSquareMeters); - Assert.False(twoSquareMeters < oneSquareMeter); - Assert.False(twoSquareMeters <= oneSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Area squaremeter = Area.FromSquareMeters(1); - Assert.Equal(0, squaremeter.CompareTo(squaremeter)); - Assert.True(squaremeter.CompareTo(Area.Zero) > 0); - Assert.True(Area.Zero.CompareTo(squaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Area squaremeter = Area.FromSquareMeters(1); - Assert.Throws(() => squaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Area squaremeter = Area.FromSquareMeters(1); - Assert.Throws(() => squaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Area a = Area.FromSquareMeters(1); - Area b = Area.FromSquareMeters(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Area v = Area.FromSquareMeters(1); - Assert.True(v.Equals(Area.FromSquareMeters(1), Area.FromSquareMeters(SquareMetersTolerance))); - Assert.False(v.Equals(Area.Zero, Area.FromSquareMeters(SquareMetersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Area squaremeter = Area.FromSquareMeters(1); - Assert.False(squaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Area squaremeter = Area.FromSquareMeters(1); - Assert.False(squaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaUnit.Undefined, Area.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/BitRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/BitRateTestsBase.g.cs deleted file mode 100644 index 6d249382a5..0000000000 --- a/UnitsNet.Tests/GeneratedCode/BitRateTestsBase.g.cs +++ /dev/null @@ -1,447 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of BitRate. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class BitRateTestsBase - { - 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; } - -// 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; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void BitPerSecondToBitRateUnits() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(BitsPerSecondInOneBitPerSecond, bitpersecond.BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(BytesPerSecondInOneBitPerSecond, bitpersecond.BytesPerSecond, BytesPerSecondTolerance); - AssertEx.EqualTolerance(ExabitsPerSecondInOneBitPerSecond, bitpersecond.ExabitsPerSecond, ExabitsPerSecondTolerance); - AssertEx.EqualTolerance(ExabytesPerSecondInOneBitPerSecond, bitpersecond.ExabytesPerSecond, ExabytesPerSecondTolerance); - AssertEx.EqualTolerance(ExbibitsPerSecondInOneBitPerSecond, bitpersecond.ExbibitsPerSecond, ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(ExbibytesPerSecondInOneBitPerSecond, bitpersecond.ExbibytesPerSecond, ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(GibibitsPerSecondInOneBitPerSecond, bitpersecond.GibibitsPerSecond, GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(GibibytesPerSecondInOneBitPerSecond, bitpersecond.GibibytesPerSecond, GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(GigabitsPerSecondInOneBitPerSecond, bitpersecond.GigabitsPerSecond, GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(GigabytesPerSecondInOneBitPerSecond, bitpersecond.GigabytesPerSecond, GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(KibibitsPerSecondInOneBitPerSecond, bitpersecond.KibibitsPerSecond, KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(KibibytesPerSecondInOneBitPerSecond, bitpersecond.KibibytesPerSecond, KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(KilobitsPerSecondInOneBitPerSecond, bitpersecond.KilobitsPerSecond, KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(KilobytesPerSecondInOneBitPerSecond, bitpersecond.KilobytesPerSecond, KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(MebibitsPerSecondInOneBitPerSecond, bitpersecond.MebibitsPerSecond, MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(MebibytesPerSecondInOneBitPerSecond, bitpersecond.MebibytesPerSecond, MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(MegabitsPerSecondInOneBitPerSecond, bitpersecond.MegabitsPerSecond, MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(MegabytesPerSecondInOneBitPerSecond, bitpersecond.MegabytesPerSecond, MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(PebibitsPerSecondInOneBitPerSecond, bitpersecond.PebibitsPerSecond, PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(PebibytesPerSecondInOneBitPerSecond, bitpersecond.PebibytesPerSecond, PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(PetabitsPerSecondInOneBitPerSecond, bitpersecond.PetabitsPerSecond, PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(PetabytesPerSecondInOneBitPerSecond, bitpersecond.PetabytesPerSecond, PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(TebibitsPerSecondInOneBitPerSecond, bitpersecond.TebibitsPerSecond, TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(TebibytesPerSecondInOneBitPerSecond, bitpersecond.TebibytesPerSecond, TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(TerabitsPerSecondInOneBitPerSecond, bitpersecond.TerabitsPerSecond, TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(TerabytesPerSecondInOneBitPerSecond, bitpersecond.TerabytesPerSecond, TerabytesPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.BitPerSecond).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.BytePerSecond).BytesPerSecond, BytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.ExabitPerSecond).ExabitsPerSecond, ExabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.ExabytePerSecond).ExabytesPerSecond, ExabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.ExbibitPerSecond).ExbibitsPerSecond, ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.ExbibytePerSecond).ExbibytesPerSecond, ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.GibibitPerSecond).GibibitsPerSecond, GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.GibibytePerSecond).GibibytesPerSecond, GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.GigabitPerSecond).GigabitsPerSecond, GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.GigabytePerSecond).GigabytesPerSecond, GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.KibibitPerSecond).KibibitsPerSecond, KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.KibibytePerSecond).KibibytesPerSecond, KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.KilobitPerSecond).KilobitsPerSecond, KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.KilobytePerSecond).KilobytesPerSecond, KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.MebibitPerSecond).MebibitsPerSecond, MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.MebibytePerSecond).MebibytesPerSecond, MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.MegabitPerSecond).MegabitsPerSecond, MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.MegabytePerSecond).MegabytesPerSecond, MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.PebibitPerSecond).PebibitsPerSecond, PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.PebibytePerSecond).PebibytesPerSecond, PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.PetabitPerSecond).PetabitsPerSecond, PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.PetabytePerSecond).PetabytesPerSecond, PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.TebibitPerSecond).TebibitsPerSecond, TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.TebibytePerSecond).TebibytesPerSecond, TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.TerabitPerSecond).TerabitsPerSecond, TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.From(1, BitRateUnit.TerabytePerSecond).TerabytesPerSecond, TerabytesPerSecondTolerance); - } - - [Fact] - public void As() - { - var bitpersecond = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(BitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.BitPerSecond), BitsPerSecondTolerance); - AssertEx.EqualTolerance(BytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.BytePerSecond), BytesPerSecondTolerance); - AssertEx.EqualTolerance(ExabitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.ExabitPerSecond), ExabitsPerSecondTolerance); - AssertEx.EqualTolerance(ExabytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.ExabytePerSecond), ExabytesPerSecondTolerance); - AssertEx.EqualTolerance(ExbibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.ExbibitPerSecond), ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(ExbibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.ExbibytePerSecond), ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(GibibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.GibibitPerSecond), GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(GibibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.GibibytePerSecond), GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(GigabitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.GigabitPerSecond), GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(GigabytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.GigabytePerSecond), GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(KibibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.KibibitPerSecond), KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(KibibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.KibibytePerSecond), KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(KilobitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.KilobitPerSecond), KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(KilobytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.KilobytePerSecond), KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(MebibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.MebibitPerSecond), MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(MebibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.MebibytePerSecond), MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(MegabitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.MegabitPerSecond), MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(MegabytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.MegabytePerSecond), MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(PebibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.PebibitPerSecond), PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(PebibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.PebibytePerSecond), PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(PetabitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.PetabitPerSecond), PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(PetabytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.PetabytePerSecond), PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(TebibitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.TebibitPerSecond), TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(TebibytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.TebibytePerSecond), TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(TerabitsPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.TerabitPerSecond), TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(TerabytesPerSecondInOneBitPerSecond, bitpersecond.As(BitRateUnit.TerabytePerSecond), TerabytesPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var bitpersecond = BitRate.FromBitsPerSecond(1); - - var bitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.BitPerSecond); - AssertEx.EqualTolerance(BitsPerSecondInOneBitPerSecond, (double)bitpersecondQuantity.Value, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, bitpersecondQuantity.Unit); - - var bytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.BytePerSecond); - AssertEx.EqualTolerance(BytesPerSecondInOneBitPerSecond, (double)bytepersecondQuantity.Value, BytesPerSecondTolerance); - Assert.Equal(BitRateUnit.BytePerSecond, bytepersecondQuantity.Unit); - - var exabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExabitPerSecond); - AssertEx.EqualTolerance(ExabitsPerSecondInOneBitPerSecond, (double)exabitpersecondQuantity.Value, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, exabitpersecondQuantity.Unit); - - var exabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExabytePerSecond); - AssertEx.EqualTolerance(ExabytesPerSecondInOneBitPerSecond, (double)exabytepersecondQuantity.Value, ExabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabytePerSecond, exabytepersecondQuantity.Unit); - - var exbibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExbibitPerSecond); - AssertEx.EqualTolerance(ExbibitsPerSecondInOneBitPerSecond, (double)exbibitpersecondQuantity.Value, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, exbibitpersecondQuantity.Unit); - - var exbibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.ExbibytePerSecond); - AssertEx.EqualTolerance(ExbibytesPerSecondInOneBitPerSecond, (double)exbibytepersecondQuantity.Value, ExbibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibytePerSecond, exbibytepersecondQuantity.Unit); - - var gibibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GibibitPerSecond); - AssertEx.EqualTolerance(GibibitsPerSecondInOneBitPerSecond, (double)gibibitpersecondQuantity.Value, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, gibibitpersecondQuantity.Unit); - - var gibibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GibibytePerSecond); - AssertEx.EqualTolerance(GibibytesPerSecondInOneBitPerSecond, (double)gibibytepersecondQuantity.Value, GibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibytePerSecond, gibibytepersecondQuantity.Unit); - - var gigabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GigabitPerSecond); - AssertEx.EqualTolerance(GigabitsPerSecondInOneBitPerSecond, (double)gigabitpersecondQuantity.Value, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, gigabitpersecondQuantity.Unit); - - var gigabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.GigabytePerSecond); - AssertEx.EqualTolerance(GigabytesPerSecondInOneBitPerSecond, (double)gigabytepersecondQuantity.Value, GigabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabytePerSecond, gigabytepersecondQuantity.Unit); - - var kibibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KibibitPerSecond); - AssertEx.EqualTolerance(KibibitsPerSecondInOneBitPerSecond, (double)kibibitpersecondQuantity.Value, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, kibibitpersecondQuantity.Unit); - - var kibibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KibibytePerSecond); - AssertEx.EqualTolerance(KibibytesPerSecondInOneBitPerSecond, (double)kibibytepersecondQuantity.Value, KibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibytePerSecond, kibibytepersecondQuantity.Unit); - - var kilobitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KilobitPerSecond); - AssertEx.EqualTolerance(KilobitsPerSecondInOneBitPerSecond, (double)kilobitpersecondQuantity.Value, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, kilobitpersecondQuantity.Unit); - - var kilobytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.KilobytePerSecond); - AssertEx.EqualTolerance(KilobytesPerSecondInOneBitPerSecond, (double)kilobytepersecondQuantity.Value, KilobytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobytePerSecond, kilobytepersecondQuantity.Unit); - - var mebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MebibitPerSecond); - AssertEx.EqualTolerance(MebibitsPerSecondInOneBitPerSecond, (double)mebibitpersecondQuantity.Value, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, mebibitpersecondQuantity.Unit); - - var mebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MebibytePerSecond); - AssertEx.EqualTolerance(MebibytesPerSecondInOneBitPerSecond, (double)mebibytepersecondQuantity.Value, MebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibytePerSecond, mebibytepersecondQuantity.Unit); - - var megabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MegabitPerSecond); - AssertEx.EqualTolerance(MegabitsPerSecondInOneBitPerSecond, (double)megabitpersecondQuantity.Value, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, megabitpersecondQuantity.Unit); - - var megabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.MegabytePerSecond); - AssertEx.EqualTolerance(MegabytesPerSecondInOneBitPerSecond, (double)megabytepersecondQuantity.Value, MegabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabytePerSecond, megabytepersecondQuantity.Unit); - - var pebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PebibitPerSecond); - AssertEx.EqualTolerance(PebibitsPerSecondInOneBitPerSecond, (double)pebibitpersecondQuantity.Value, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, pebibitpersecondQuantity.Unit); - - var pebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PebibytePerSecond); - AssertEx.EqualTolerance(PebibytesPerSecondInOneBitPerSecond, (double)pebibytepersecondQuantity.Value, PebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibytePerSecond, pebibytepersecondQuantity.Unit); - - var petabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PetabitPerSecond); - AssertEx.EqualTolerance(PetabitsPerSecondInOneBitPerSecond, (double)petabitpersecondQuantity.Value, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, petabitpersecondQuantity.Unit); - - var petabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.PetabytePerSecond); - AssertEx.EqualTolerance(PetabytesPerSecondInOneBitPerSecond, (double)petabytepersecondQuantity.Value, PetabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabytePerSecond, petabytepersecondQuantity.Unit); - - var tebibitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TebibitPerSecond); - AssertEx.EqualTolerance(TebibitsPerSecondInOneBitPerSecond, (double)tebibitpersecondQuantity.Value, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, tebibitpersecondQuantity.Unit); - - var tebibytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TebibytePerSecond); - AssertEx.EqualTolerance(TebibytesPerSecondInOneBitPerSecond, (double)tebibytepersecondQuantity.Value, TebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibytePerSecond, tebibytepersecondQuantity.Unit); - - var terabitpersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TerabitPerSecond); - AssertEx.EqualTolerance(TerabitsPerSecondInOneBitPerSecond, (double)terabitpersecondQuantity.Value, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, terabitpersecondQuantity.Unit); - - var terabytepersecondQuantity = bitpersecond.ToUnit(BitRateUnit.TerabytePerSecond); - AssertEx.EqualTolerance(TerabytesPerSecondInOneBitPerSecond, (double)terabytepersecondQuantity.Value, TerabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabytePerSecond, terabytepersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(1, BitRate.FromBitsPerSecond(bitpersecond.BitsPerSecond).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromBytesPerSecond(bitpersecond.BytesPerSecond).BitsPerSecond, BytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExabitsPerSecond(bitpersecond.ExabitsPerSecond).BitsPerSecond, ExabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExabytesPerSecond(bitpersecond.ExabytesPerSecond).BitsPerSecond, ExabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbibitsPerSecond(bitpersecond.ExbibitsPerSecond).BitsPerSecond, ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbibytesPerSecond(bitpersecond.ExbibytesPerSecond).BitsPerSecond, ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibitsPerSecond(bitpersecond.GibibitsPerSecond).BitsPerSecond, GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibytesPerSecond(bitpersecond.GibibytesPerSecond).BitsPerSecond, GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabitsPerSecond(bitpersecond.GigabitsPerSecond).BitsPerSecond, GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabytesPerSecond(bitpersecond.GigabytesPerSecond).BitsPerSecond, GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibitsPerSecond(bitpersecond.KibibitsPerSecond).BitsPerSecond, KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibytesPerSecond(bitpersecond.KibibytesPerSecond).BitsPerSecond, KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobitsPerSecond(bitpersecond.KilobitsPerSecond).BitsPerSecond, KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobytesPerSecond(bitpersecond.KilobytesPerSecond).BitsPerSecond, KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibitsPerSecond(bitpersecond.MebibitsPerSecond).BitsPerSecond, MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibytesPerSecond(bitpersecond.MebibytesPerSecond).BitsPerSecond, MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabitsPerSecond(bitpersecond.MegabitsPerSecond).BitsPerSecond, MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabytesPerSecond(bitpersecond.MegabytesPerSecond).BitsPerSecond, MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibitsPerSecond(bitpersecond.PebibitsPerSecond).BitsPerSecond, PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibytesPerSecond(bitpersecond.PebibytesPerSecond).BitsPerSecond, PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabitsPerSecond(bitpersecond.PetabitsPerSecond).BitsPerSecond, PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabytesPerSecond(bitpersecond.PetabytesPerSecond).BitsPerSecond, PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibitsPerSecond(bitpersecond.TebibitsPerSecond).BitsPerSecond, TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibytesPerSecond(bitpersecond.TebibytesPerSecond).BitsPerSecond, TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabitsPerSecond(bitpersecond.TerabitsPerSecond).BitsPerSecond, TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabytesPerSecond(bitpersecond.TerabytesPerSecond).BitsPerSecond, TerabytesPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - BitRate v = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (BitRate.FromBitsPerSecond(3)-v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (BitRate.FromBitsPerSecond(10)/5).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, BitRate.FromBitsPerSecond(10)/BitRate.FromBitsPerSecond(5), BitsPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - BitRate oneBitPerSecond = BitRate.FromBitsPerSecond(1); - BitRate twoBitsPerSecond = BitRate.FromBitsPerSecond(2); - - Assert.True(oneBitPerSecond < twoBitsPerSecond); - Assert.True(oneBitPerSecond <= twoBitsPerSecond); - Assert.True(twoBitsPerSecond > oneBitPerSecond); - Assert.True(twoBitsPerSecond >= oneBitPerSecond); - - Assert.False(oneBitPerSecond > twoBitsPerSecond); - Assert.False(oneBitPerSecond >= twoBitsPerSecond); - Assert.False(twoBitsPerSecond < oneBitPerSecond); - Assert.False(twoBitsPerSecond <= oneBitPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - Assert.Equal(0, bitpersecond.CompareTo(bitpersecond)); - Assert.True(bitpersecond.CompareTo(BitRate.Zero) > 0); - Assert.True(BitRate.Zero.CompareTo(bitpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - Assert.Throws(() => bitpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - Assert.Throws(() => bitpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - BitRate a = BitRate.FromBitsPerSecond(1); - BitRate b = BitRate.FromBitsPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - BitRate v = BitRate.FromBitsPerSecond(1); - Assert.True(v.Equals(BitRate.FromBitsPerSecond(1), BitRate.FromBitsPerSecond(BitsPerSecondTolerance))); - Assert.False(v.Equals(BitRate.Zero, BitRate.FromBitsPerSecond(BitsPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - Assert.False(bitpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - Assert.False(bitpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(BitRateUnit.Undefined, BitRate.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/BrakeSpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/BrakeSpecificFuelConsumptionTestsBase.g.cs deleted file mode 100644 index 04aa19ffc5..0000000000 --- a/UnitsNet.Tests/GeneratedCode/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of BrakeSpecificFuelConsumption. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class BrakeSpecificFuelConsumptionTestsBase - { - protected abstract double GramsPerKiloWattHourInOneKilogramPerJoule { get; } - protected abstract double KilogramsPerJouleInOneKilogramPerJoule { get; } - protected abstract double PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerKiloWattHourTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerJouleTolerance { get { return 1e-5; } } - protected virtual double PoundsPerMechanicalHorsepowerHourTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerJouleToBrakeSpecificFuelConsumptionUnits() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(GramsPerKiloWattHourInOneKilogramPerJoule, kilogramperjoule.GramsPerKiloWattHour, GramsPerKiloWattHourTolerance); - AssertEx.EqualTolerance(KilogramsPerJouleInOneKilogramPerJoule, kilogramperjoule.KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule, kilogramperjoule.PoundsPerMechanicalHorsepowerHour, PoundsPerMechanicalHorsepowerHourTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour).GramsPerKiloWattHour, GramsPerKiloWattHourTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour).PoundsPerMechanicalHorsepowerHour, PoundsPerMechanicalHorsepowerHourTolerance); - } - - [Fact] - public void As() - { - var kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(GramsPerKiloWattHourInOneKilogramPerJoule, kilogramperjoule.As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour), GramsPerKiloWattHourTolerance); - AssertEx.EqualTolerance(KilogramsPerJouleInOneKilogramPerJoule, kilogramperjoule.As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule), KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule, kilogramperjoule.As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour), PoundsPerMechanicalHorsepowerHourTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - - var gramperkilowatthourQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - AssertEx.EqualTolerance(GramsPerKiloWattHourInOneKilogramPerJoule, (double)gramperkilowatthourQuantity.Value, GramsPerKiloWattHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, gramperkilowatthourQuantity.Unit); - - var kilogramperjouleQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - AssertEx.EqualTolerance(KilogramsPerJouleInOneKilogramPerJoule, (double)kilogramperjouleQuantity.Value, KilogramsPerJouleTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, kilogramperjouleQuantity.Unit); - - var poundpermechanicalhorsepowerhourQuantity = kilogramperjoule.ToUnit(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - AssertEx.EqualTolerance(PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule, (double)poundpermechanicalhorsepowerhourQuantity.Value, PoundsPerMechanicalHorsepowerHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, poundpermechanicalhorsepowerhourQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(kilogramperjoule.GramsPerKiloWattHour).KilogramsPerJoule, GramsPerKiloWattHourTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(kilogramperjoule.KilogramsPerJoule).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(kilogramperjoule.PoundsPerMechanicalHorsepowerHour).KilogramsPerJoule, PoundsPerMechanicalHorsepowerHourTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - BrakeSpecificFuelConsumption v = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(3)-v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10)/5).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10)/BrakeSpecificFuelConsumption.FromKilogramsPerJoule(5), KilogramsPerJouleTolerance); - } - - [Fact] - public void ComparisonOperators() - { - BrakeSpecificFuelConsumption oneKilogramPerJoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - BrakeSpecificFuelConsumption twoKilogramsPerJoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(2); - - Assert.True(oneKilogramPerJoule < twoKilogramsPerJoule); - Assert.True(oneKilogramPerJoule <= twoKilogramsPerJoule); - Assert.True(twoKilogramsPerJoule > oneKilogramPerJoule); - Assert.True(twoKilogramsPerJoule >= oneKilogramPerJoule); - - Assert.False(oneKilogramPerJoule > twoKilogramsPerJoule); - Assert.False(oneKilogramPerJoule >= twoKilogramsPerJoule); - Assert.False(twoKilogramsPerJoule < oneKilogramPerJoule); - Assert.False(twoKilogramsPerJoule <= oneKilogramPerJoule); - } - - [Fact] - public void CompareToIsImplemented() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.Equal(0, kilogramperjoule.CompareTo(kilogramperjoule)); - Assert.True(kilogramperjoule.CompareTo(BrakeSpecificFuelConsumption.Zero) > 0); - Assert.True(BrakeSpecificFuelConsumption.Zero.CompareTo(kilogramperjoule) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.Throws(() => kilogramperjoule.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.Throws(() => kilogramperjoule.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - BrakeSpecificFuelConsumption a = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - BrakeSpecificFuelConsumption b = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - BrakeSpecificFuelConsumption v = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.True(v.Equals(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1), BrakeSpecificFuelConsumption.FromKilogramsPerJoule(KilogramsPerJouleTolerance))); - Assert.False(v.Equals(BrakeSpecificFuelConsumption.Zero, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(KilogramsPerJouleTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.False(kilogramperjoule.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.False(kilogramperjoule.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(BrakeSpecificFuelConsumptionUnit.Undefined, BrakeSpecificFuelConsumption.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/CapacitanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/CapacitanceTestsBase.g.cs deleted file mode 100644 index fd3a45f621..0000000000 --- a/UnitsNet.Tests/GeneratedCode/CapacitanceTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Capacitance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class CapacitanceTestsBase - { - protected abstract double FaradsInOneFarad { get; } - protected abstract double MicrofaradsInOneFarad { get; } - protected abstract double MillifaradsInOneFarad { get; } - protected abstract double NanofaradsInOneFarad { get; } - protected abstract double PicofaradsInOneFarad { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double FaradsTolerance { get { return 1e-5; } } - protected virtual double MicrofaradsTolerance { get { return 1e-5; } } - protected virtual double MillifaradsTolerance { get { return 1e-5; } } - protected virtual double NanofaradsTolerance { get { return 1e-5; } } - protected virtual double PicofaradsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void FaradToCapacitanceUnits() - { - Capacitance farad = Capacitance.FromFarads(1); - AssertEx.EqualTolerance(FaradsInOneFarad, farad.Farads, FaradsTolerance); - AssertEx.EqualTolerance(MicrofaradsInOneFarad, farad.Microfarads, MicrofaradsTolerance); - AssertEx.EqualTolerance(MillifaradsInOneFarad, farad.Millifarads, MillifaradsTolerance); - AssertEx.EqualTolerance(NanofaradsInOneFarad, farad.Nanofarads, NanofaradsTolerance); - AssertEx.EqualTolerance(PicofaradsInOneFarad, farad.Picofarads, PicofaradsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Capacitance.From(1, CapacitanceUnit.Farad).Farads, FaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.From(1, CapacitanceUnit.Microfarad).Microfarads, MicrofaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.From(1, CapacitanceUnit.Millifarad).Millifarads, MillifaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.From(1, CapacitanceUnit.Nanofarad).Nanofarads, NanofaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.From(1, CapacitanceUnit.Picofarad).Picofarads, PicofaradsTolerance); - } - - [Fact] - public void As() - { - var farad = Capacitance.FromFarads(1); - AssertEx.EqualTolerance(FaradsInOneFarad, farad.As(CapacitanceUnit.Farad), FaradsTolerance); - AssertEx.EqualTolerance(MicrofaradsInOneFarad, farad.As(CapacitanceUnit.Microfarad), MicrofaradsTolerance); - AssertEx.EqualTolerance(MillifaradsInOneFarad, farad.As(CapacitanceUnit.Millifarad), MillifaradsTolerance); - AssertEx.EqualTolerance(NanofaradsInOneFarad, farad.As(CapacitanceUnit.Nanofarad), NanofaradsTolerance); - AssertEx.EqualTolerance(PicofaradsInOneFarad, farad.As(CapacitanceUnit.Picofarad), PicofaradsTolerance); - } - - [Fact] - public void ToUnit() - { - var farad = Capacitance.FromFarads(1); - - var faradQuantity = farad.ToUnit(CapacitanceUnit.Farad); - AssertEx.EqualTolerance(FaradsInOneFarad, (double)faradQuantity.Value, FaradsTolerance); - Assert.Equal(CapacitanceUnit.Farad, faradQuantity.Unit); - - var microfaradQuantity = farad.ToUnit(CapacitanceUnit.Microfarad); - AssertEx.EqualTolerance(MicrofaradsInOneFarad, (double)microfaradQuantity.Value, MicrofaradsTolerance); - Assert.Equal(CapacitanceUnit.Microfarad, microfaradQuantity.Unit); - - var millifaradQuantity = farad.ToUnit(CapacitanceUnit.Millifarad); - AssertEx.EqualTolerance(MillifaradsInOneFarad, (double)millifaradQuantity.Value, MillifaradsTolerance); - Assert.Equal(CapacitanceUnit.Millifarad, millifaradQuantity.Unit); - - var nanofaradQuantity = farad.ToUnit(CapacitanceUnit.Nanofarad); - AssertEx.EqualTolerance(NanofaradsInOneFarad, (double)nanofaradQuantity.Value, NanofaradsTolerance); - Assert.Equal(CapacitanceUnit.Nanofarad, nanofaradQuantity.Unit); - - var picofaradQuantity = farad.ToUnit(CapacitanceUnit.Picofarad); - AssertEx.EqualTolerance(PicofaradsInOneFarad, (double)picofaradQuantity.Value, PicofaradsTolerance); - Assert.Equal(CapacitanceUnit.Picofarad, picofaradQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Capacitance farad = Capacitance.FromFarads(1); - AssertEx.EqualTolerance(1, Capacitance.FromFarads(farad.Farads).Farads, FaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.FromMicrofarads(farad.Microfarads).Farads, MicrofaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.FromMillifarads(farad.Millifarads).Farads, MillifaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.FromNanofarads(farad.Nanofarads).Farads, NanofaradsTolerance); - AssertEx.EqualTolerance(1, Capacitance.FromPicofarads(farad.Picofarads).Farads, PicofaradsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Capacitance v = Capacitance.FromFarads(1); - AssertEx.EqualTolerance(-1, -v.Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (Capacitance.FromFarads(3)-v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (v + v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(10, (v*10).Farads, FaradsTolerance); - AssertEx.EqualTolerance(10, (10*v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (Capacitance.FromFarads(10)/5).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, Capacitance.FromFarads(10)/Capacitance.FromFarads(5), FaradsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Capacitance oneFarad = Capacitance.FromFarads(1); - Capacitance twoFarads = Capacitance.FromFarads(2); - - Assert.True(oneFarad < twoFarads); - Assert.True(oneFarad <= twoFarads); - Assert.True(twoFarads > oneFarad); - Assert.True(twoFarads >= oneFarad); - - Assert.False(oneFarad > twoFarads); - Assert.False(oneFarad >= twoFarads); - Assert.False(twoFarads < oneFarad); - Assert.False(twoFarads <= oneFarad); - } - - [Fact] - public void CompareToIsImplemented() - { - Capacitance farad = Capacitance.FromFarads(1); - Assert.Equal(0, farad.CompareTo(farad)); - Assert.True(farad.CompareTo(Capacitance.Zero) > 0); - Assert.True(Capacitance.Zero.CompareTo(farad) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Capacitance farad = Capacitance.FromFarads(1); - Assert.Throws(() => farad.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Capacitance farad = Capacitance.FromFarads(1); - Assert.Throws(() => farad.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Capacitance a = Capacitance.FromFarads(1); - Capacitance b = Capacitance.FromFarads(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Capacitance v = Capacitance.FromFarads(1); - Assert.True(v.Equals(Capacitance.FromFarads(1), Capacitance.FromFarads(FaradsTolerance))); - Assert.False(v.Equals(Capacitance.Zero, Capacitance.FromFarads(FaradsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Capacitance farad = Capacitance.FromFarads(1); - Assert.False(farad.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Capacitance farad = Capacitance.FromFarads(1); - Assert.False(farad.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(CapacitanceUnit.Undefined, Capacitance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/CoefficientOfThermalExpansionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/CoefficientOfThermalExpansionTestsBase.g.cs deleted file mode 100644 index b9cbd62f25..0000000000 --- a/UnitsNet.Tests/GeneratedCode/CoefficientOfThermalExpansionTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of CoefficientOfThermalExpansion. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class CoefficientOfThermalExpansionTestsBase - { - protected abstract double InverseDegreeCelsiusInOneInverseKelvin { get; } - protected abstract double InverseDegreeFahrenheitInOneInverseKelvin { get; } - protected abstract double InverseKelvinInOneInverseKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InverseDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double InverseDegreeFahrenheitTolerance { get { return 1e-5; } } - protected virtual double InverseKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void InverseKelvinToCoefficientOfThermalExpansionUnits() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - AssertEx.EqualTolerance(InverseDegreeCelsiusInOneInverseKelvin, inversekelvin.InverseDegreeCelsius, InverseDegreeCelsiusTolerance); - AssertEx.EqualTolerance(InverseDegreeFahrenheitInOneInverseKelvin, inversekelvin.InverseDegreeFahrenheit, InverseDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(InverseKelvinInOneInverseKelvin, inversekelvin.InverseKelvin, InverseKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius).InverseDegreeCelsius, InverseDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit).InverseDegreeFahrenheit, InverseDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.InverseKelvin).InverseKelvin, InverseKelvinTolerance); - } - - [Fact] - public void As() - { - var inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - AssertEx.EqualTolerance(InverseDegreeCelsiusInOneInverseKelvin, inversekelvin.As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius), InverseDegreeCelsiusTolerance); - AssertEx.EqualTolerance(InverseDegreeFahrenheitInOneInverseKelvin, inversekelvin.As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit), InverseDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(InverseKelvinInOneInverseKelvin, inversekelvin.As(CoefficientOfThermalExpansionUnit.InverseKelvin), InverseKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - - var inversedegreecelsiusQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - AssertEx.EqualTolerance(InverseDegreeCelsiusInOneInverseKelvin, (double)inversedegreecelsiusQuantity.Value, InverseDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, inversedegreecelsiusQuantity.Unit); - - var inversedegreefahrenheitQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - AssertEx.EqualTolerance(InverseDegreeFahrenheitInOneInverseKelvin, (double)inversedegreefahrenheitQuantity.Value, InverseDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, inversedegreefahrenheitQuantity.Unit); - - var inversekelvinQuantity = inversekelvin.ToUnit(CoefficientOfThermalExpansionUnit.InverseKelvin); - AssertEx.EqualTolerance(InverseKelvinInOneInverseKelvin, (double)inversekelvinQuantity.Value, InverseKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.InverseKelvin, inversekelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromInverseDegreeCelsius(inversekelvin.InverseDegreeCelsius).InverseKelvin, InverseDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromInverseDegreeFahrenheit(inversekelvin.InverseDegreeFahrenheit).InverseKelvin, InverseDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromInverseKelvin(inversekelvin.InverseKelvin).InverseKelvin, InverseKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - CoefficientOfThermalExpansion v = CoefficientOfThermalExpansion.FromInverseKelvin(1); - AssertEx.EqualTolerance(-1, -v.InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(2, (CoefficientOfThermalExpansion.FromInverseKelvin(3)-v).InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(2, (CoefficientOfThermalExpansion.FromInverseKelvin(10)/5).InverseKelvin, InverseKelvinTolerance); - AssertEx.EqualTolerance(2, CoefficientOfThermalExpansion.FromInverseKelvin(10)/CoefficientOfThermalExpansion.FromInverseKelvin(5), InverseKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - CoefficientOfThermalExpansion oneInverseKelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - CoefficientOfThermalExpansion twoInverseKelvin = CoefficientOfThermalExpansion.FromInverseKelvin(2); - - Assert.True(oneInverseKelvin < twoInverseKelvin); - Assert.True(oneInverseKelvin <= twoInverseKelvin); - Assert.True(twoInverseKelvin > oneInverseKelvin); - Assert.True(twoInverseKelvin >= oneInverseKelvin); - - Assert.False(oneInverseKelvin > twoInverseKelvin); - Assert.False(oneInverseKelvin >= twoInverseKelvin); - Assert.False(twoInverseKelvin < oneInverseKelvin); - Assert.False(twoInverseKelvin <= oneInverseKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.Equal(0, inversekelvin.CompareTo(inversekelvin)); - Assert.True(inversekelvin.CompareTo(CoefficientOfThermalExpansion.Zero) > 0); - Assert.True(CoefficientOfThermalExpansion.Zero.CompareTo(inversekelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.Throws(() => inversekelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.Throws(() => inversekelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - CoefficientOfThermalExpansion a = CoefficientOfThermalExpansion.FromInverseKelvin(1); - CoefficientOfThermalExpansion b = CoefficientOfThermalExpansion.FromInverseKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - CoefficientOfThermalExpansion v = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.True(v.Equals(CoefficientOfThermalExpansion.FromInverseKelvin(1), CoefficientOfThermalExpansion.FromInverseKelvin(InverseKelvinTolerance))); - Assert.False(v.Equals(CoefficientOfThermalExpansion.Zero, CoefficientOfThermalExpansion.FromInverseKelvin(InverseKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.False(inversekelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - CoefficientOfThermalExpansion inversekelvin = CoefficientOfThermalExpansion.FromInverseKelvin(1); - Assert.False(inversekelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(CoefficientOfThermalExpansionUnit.Undefined, CoefficientOfThermalExpansion.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/DensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/DensityTestsBase.g.cs deleted file mode 100644 index 3a721ca51e..0000000000 --- a/UnitsNet.Tests/GeneratedCode/DensityTestsBase.g.cs +++ /dev/null @@ -1,567 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Density. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class DensityTestsBase - { - protected abstract double CentigramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double CentigramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double CentigramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double DecigramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double DecigramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double DecigramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerCubicCentimeterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerCubicMeterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerCubicMillimeterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double GramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter { get; } - protected abstract double KilogramsPerCubicMeterInOneKilogramPerCubicMeter { get; } - protected abstract double KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter { get; } - protected abstract double KilopoundsPerCubicFootInOneKilogramPerCubicMeter { get; } - protected abstract double KilopoundsPerCubicInchInOneKilogramPerCubicMeter { get; } - protected abstract double MicrogramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double MicrogramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double MicrogramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double MilligramsPerCubicMeterInOneKilogramPerCubicMeter { get; } - protected abstract double MilligramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double MilligramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double MilligramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double NanogramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double NanogramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double NanogramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double PicogramsPerDeciLiterInOneKilogramPerCubicMeter { get; } - protected abstract double PicogramsPerLiterInOneKilogramPerCubicMeter { get; } - protected abstract double PicogramsPerMilliliterInOneKilogramPerCubicMeter { get; } - protected abstract double PoundsPerCubicFootInOneKilogramPerCubicMeter { get; } - protected abstract double PoundsPerCubicInchInOneKilogramPerCubicMeter { get; } - protected abstract double PoundsPerImperialGallonInOneKilogramPerCubicMeter { get; } - protected abstract double PoundsPerUSGallonInOneKilogramPerCubicMeter { get; } - protected abstract double SlugsPerCubicFootInOneKilogramPerCubicMeter { get; } - protected abstract double TonnesPerCubicCentimeterInOneKilogramPerCubicMeter { get; } - protected abstract double TonnesPerCubicMeterInOneKilogramPerCubicMeter { get; } - protected abstract double TonnesPerCubicMillimeterInOneKilogramPerCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double CentigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double GramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double GramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double GramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerDeciLiterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicogramsPerMilliliterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PoundsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double PoundsPerImperialGallonTolerance { get { return 1e-5; } } - protected virtual double PoundsPerUSGallonTolerance { get { return 1e-5; } } - protected virtual double SlugsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesPerCubicMillimeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerCubicMeterToDensityUnits() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(CentigramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.CentigramsPerDeciLiter, CentigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(CentigramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.CentigramsPerLiter, CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(CentigramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(DecigramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.DecigramsPerDeciLiter, DecigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(DecigramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.DecigramsPerLiter, DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(DecigramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(GramsPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(GramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(GramsPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(GramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerDeciLiter, GramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(GramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerLiter, GramsPerLiterTolerance); - AssertEx.EqualTolerance(GramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.GramsPerMilliliter, GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilopoundsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(KilopoundsPerCubicInchInOneKilogramPerCubicMeter, kilogrampercubicmeter.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(MicrogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MicrogramsPerDeciLiter, MicrogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(MicrogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MicrogramsPerLiter, MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(MicrogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(MilligramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MilligramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MilligramsPerDeciLiter, MilligramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(MilligramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MilligramsPerLiter, MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(MilligramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(NanogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.NanogramsPerDeciLiter, NanogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(NanogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.NanogramsPerLiter, NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(NanogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(PicogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.PicogramsPerDeciLiter, PicogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(PicogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.PicogramsPerLiter, PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(PicogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(PoundsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(PoundsPerCubicInchInOneKilogramPerCubicMeter, kilogrampercubicmeter.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(PoundsPerImperialGallonInOneKilogramPerCubicMeter, kilogrampercubicmeter.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(PoundsPerUSGallonInOneKilogramPerCubicMeter, kilogrampercubicmeter.PoundsPerUSGallon, PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(SlugsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(TonnesPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.CentigramPerDeciliter).CentigramsPerDeciLiter, CentigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.CentigramPerLiter).CentigramsPerLiter, CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.CentigramPerMilliliter).CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.DecigramPerDeciliter).DecigramsPerDeciLiter, DecigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.DecigramPerLiter).DecigramsPerLiter, DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.DecigramPerMilliliter).DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerCubicCentimeter).GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerCubicMeter).GramsPerCubicMeter, GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerCubicMillimeter).GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerDeciliter).GramsPerDeciLiter, GramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerLiter).GramsPerLiter, GramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.GramPerMilliliter).GramsPerMilliliter, GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.KilogramPerCubicCentimeter).KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.KilogramPerCubicMeter).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.KilogramPerCubicMillimeter).KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.KilopoundPerCubicFoot).KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.KilopoundPerCubicInch).KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MicrogramPerDeciliter).MicrogramsPerDeciLiter, MicrogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MicrogramPerLiter).MicrogramsPerLiter, MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MicrogramPerMilliliter).MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MilligramPerCubicMeter).MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MilligramPerDeciliter).MilligramsPerDeciLiter, MilligramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MilligramPerLiter).MilligramsPerLiter, MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.MilligramPerMilliliter).MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.NanogramPerDeciliter).NanogramsPerDeciLiter, NanogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.NanogramPerLiter).NanogramsPerLiter, NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.NanogramPerMilliliter).NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PicogramPerDeciliter).PicogramsPerDeciLiter, PicogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PicogramPerLiter).PicogramsPerLiter, PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PicogramPerMilliliter).PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PoundPerCubicFoot).PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PoundPerCubicInch).PoundsPerCubicInch, PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PoundPerImperialGallon).PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.PoundPerUSGallon).PoundsPerUSGallon, PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.SlugPerCubicFoot).SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.TonnePerCubicCentimeter).TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.TonnePerCubicMeter).TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.From(1, DensityUnit.TonnePerCubicMillimeter).TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - } - - [Fact] - public void As() - { - var kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(CentigramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.CentigramPerDeciliter), CentigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(CentigramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.CentigramPerLiter), CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(CentigramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.CentigramPerMilliliter), CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(DecigramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.DecigramPerDeciliter), DecigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(DecigramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.DecigramPerLiter), DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(DecigramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.DecigramPerMilliliter), DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(GramsPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerCubicCentimeter), GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(GramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerCubicMeter), GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(GramsPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerCubicMillimeter), GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(GramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerDeciliter), GramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(GramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerLiter), GramsPerLiterTolerance); - AssertEx.EqualTolerance(GramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.GramPerMilliliter), GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.KilogramPerCubicCentimeter), KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.KilogramPerCubicMeter), KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.KilogramPerCubicMillimeter), KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilopoundsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.KilopoundPerCubicFoot), KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(KilopoundsPerCubicInchInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.KilopoundPerCubicInch), KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(MicrogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MicrogramPerDeciliter), MicrogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(MicrogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MicrogramPerLiter), MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(MicrogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MicrogramPerMilliliter), MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(MilligramsPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MilligramPerCubicMeter), MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MilligramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MilligramPerDeciliter), MilligramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(MilligramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MilligramPerLiter), MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(MilligramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.MilligramPerMilliliter), MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(NanogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.NanogramPerDeciliter), NanogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(NanogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.NanogramPerLiter), NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(NanogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.NanogramPerMilliliter), NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(PicogramsPerDeciLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PicogramPerDeciliter), PicogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(PicogramsPerLiterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PicogramPerLiter), PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(PicogramsPerMilliliterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PicogramPerMilliliter), PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(PoundsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PoundPerCubicFoot), PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(PoundsPerCubicInchInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PoundPerCubicInch), PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(PoundsPerImperialGallonInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PoundPerImperialGallon), PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(PoundsPerUSGallonInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.PoundPerUSGallon), PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(SlugsPerCubicFootInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.SlugPerCubicFoot), SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.TonnePerCubicCentimeter), TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(TonnesPerCubicMeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.TonnePerCubicMeter), TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, kilogrampercubicmeter.As(DensityUnit.TonnePerCubicMillimeter), TonnesPerCubicMillimeterTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - - var centigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerDeciliter); - AssertEx.EqualTolerance(CentigramsPerDeciLiterInOneKilogramPerCubicMeter, (double)centigramperdeciliterQuantity.Value, CentigramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerDeciliter, centigramperdeciliterQuantity.Unit); - - var centigramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerLiter); - AssertEx.EqualTolerance(CentigramsPerLiterInOneKilogramPerCubicMeter, (double)centigramperliterQuantity.Value, CentigramsPerLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerLiter, centigramperliterQuantity.Unit); - - var centigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.CentigramPerMilliliter); - AssertEx.EqualTolerance(CentigramsPerMilliliterInOneKilogramPerCubicMeter, (double)centigrampermilliliterQuantity.Value, CentigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.CentigramPerMilliliter, centigrampermilliliterQuantity.Unit); - - var decigramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerDeciliter); - AssertEx.EqualTolerance(DecigramsPerDeciLiterInOneKilogramPerCubicMeter, (double)decigramperdeciliterQuantity.Value, DecigramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerDeciliter, decigramperdeciliterQuantity.Unit); - - var decigramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerLiter); - AssertEx.EqualTolerance(DecigramsPerLiterInOneKilogramPerCubicMeter, (double)decigramperliterQuantity.Value, DecigramsPerLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerLiter, decigramperliterQuantity.Unit); - - var decigrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.DecigramPerMilliliter); - AssertEx.EqualTolerance(DecigramsPerMilliliterInOneKilogramPerCubicMeter, (double)decigrampermilliliterQuantity.Value, DecigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.DecigramPerMilliliter, decigrampermilliliterQuantity.Unit); - - var grampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicCentimeter); - AssertEx.EqualTolerance(GramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)grampercubiccentimeterQuantity.Value, GramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicCentimeter, grampercubiccentimeterQuantity.Unit); - - var grampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicMeter); - AssertEx.EqualTolerance(GramsPerCubicMeterInOneKilogramPerCubicMeter, (double)grampercubicmeterQuantity.Value, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, grampercubicmeterQuantity.Unit); - - var grampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerCubicMillimeter); - AssertEx.EqualTolerance(GramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)grampercubicmillimeterQuantity.Value, GramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMillimeter, grampercubicmillimeterQuantity.Unit); - - var gramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerDeciliter); - AssertEx.EqualTolerance(GramsPerDeciLiterInOneKilogramPerCubicMeter, (double)gramperdeciliterQuantity.Value, GramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.GramPerDeciliter, gramperdeciliterQuantity.Unit); - - var gramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerLiter); - AssertEx.EqualTolerance(GramsPerLiterInOneKilogramPerCubicMeter, (double)gramperliterQuantity.Value, GramsPerLiterTolerance); - Assert.Equal(DensityUnit.GramPerLiter, gramperliterQuantity.Unit); - - var grampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.GramPerMilliliter); - AssertEx.EqualTolerance(GramsPerMilliliterInOneKilogramPerCubicMeter, (double)grampermilliliterQuantity.Value, GramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.GramPerMilliliter, grampermilliliterQuantity.Unit); - - var kilogrampercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicCentimeter); - AssertEx.EqualTolerance(KilogramsPerCubicCentimeterInOneKilogramPerCubicMeter, (double)kilogrampercubiccentimeterQuantity.Value, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicCentimeter, kilogrampercubiccentimeterQuantity.Unit); - - var kilogrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicMeter); - AssertEx.EqualTolerance(KilogramsPerCubicMeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmeterQuantity.Value, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, kilogrampercubicmeterQuantity.Unit); - - var kilogrampercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilogramPerCubicMillimeter); - AssertEx.EqualTolerance(KilogramsPerCubicMillimeterInOneKilogramPerCubicMeter, (double)kilogrampercubicmillimeterQuantity.Value, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMillimeter, kilogrampercubicmillimeterQuantity.Unit); - - var kilopoundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilopoundPerCubicFoot); - AssertEx.EqualTolerance(KilopoundsPerCubicFootInOneKilogramPerCubicMeter, (double)kilopoundpercubicfootQuantity.Value, KilopoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicFoot, kilopoundpercubicfootQuantity.Unit); - - var kilopoundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.KilopoundPerCubicInch); - AssertEx.EqualTolerance(KilopoundsPerCubicInchInOneKilogramPerCubicMeter, (double)kilopoundpercubicinchQuantity.Value, KilopoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicInch, kilopoundpercubicinchQuantity.Unit); - - var microgramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerDeciliter); - AssertEx.EqualTolerance(MicrogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)microgramperdeciliterQuantity.Value, MicrogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerDeciliter, microgramperdeciliterQuantity.Unit); - - var microgramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerLiter); - AssertEx.EqualTolerance(MicrogramsPerLiterInOneKilogramPerCubicMeter, (double)microgramperliterQuantity.Value, MicrogramsPerLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerLiter, microgramperliterQuantity.Unit); - - var microgrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MicrogramPerMilliliter); - AssertEx.EqualTolerance(MicrogramsPerMilliliterInOneKilogramPerCubicMeter, (double)microgrampermilliliterQuantity.Value, MicrogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerMilliliter, microgrampermilliliterQuantity.Unit); - - var milligrampercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerCubicMeter); - AssertEx.EqualTolerance(MilligramsPerCubicMeterInOneKilogramPerCubicMeter, (double)milligrampercubicmeterQuantity.Value, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, milligrampercubicmeterQuantity.Unit); - - var milligramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerDeciliter); - AssertEx.EqualTolerance(MilligramsPerDeciLiterInOneKilogramPerCubicMeter, (double)milligramperdeciliterQuantity.Value, MilligramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerDeciliter, milligramperdeciliterQuantity.Unit); - - var milligramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerLiter); - AssertEx.EqualTolerance(MilligramsPerLiterInOneKilogramPerCubicMeter, (double)milligramperliterQuantity.Value, MilligramsPerLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerLiter, milligramperliterQuantity.Unit); - - var milligrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.MilligramPerMilliliter); - AssertEx.EqualTolerance(MilligramsPerMilliliterInOneKilogramPerCubicMeter, (double)milligrampermilliliterQuantity.Value, MilligramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MilligramPerMilliliter, milligrampermilliliterQuantity.Unit); - - var nanogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerDeciliter); - AssertEx.EqualTolerance(NanogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)nanogramperdeciliterQuantity.Value, NanogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerDeciliter, nanogramperdeciliterQuantity.Unit); - - var nanogramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerLiter); - AssertEx.EqualTolerance(NanogramsPerLiterInOneKilogramPerCubicMeter, (double)nanogramperliterQuantity.Value, NanogramsPerLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerLiter, nanogramperliterQuantity.Unit); - - var nanogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.NanogramPerMilliliter); - AssertEx.EqualTolerance(NanogramsPerMilliliterInOneKilogramPerCubicMeter, (double)nanogrampermilliliterQuantity.Value, NanogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.NanogramPerMilliliter, nanogrampermilliliterQuantity.Unit); - - var picogramperdeciliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerDeciliter); - AssertEx.EqualTolerance(PicogramsPerDeciLiterInOneKilogramPerCubicMeter, (double)picogramperdeciliterQuantity.Value, PicogramsPerDeciLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerDeciliter, picogramperdeciliterQuantity.Unit); - - var picogramperliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerLiter); - AssertEx.EqualTolerance(PicogramsPerLiterInOneKilogramPerCubicMeter, (double)picogramperliterQuantity.Value, PicogramsPerLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerLiter, picogramperliterQuantity.Unit); - - var picogrampermilliliterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PicogramPerMilliliter); - AssertEx.EqualTolerance(PicogramsPerMilliliterInOneKilogramPerCubicMeter, (double)picogrampermilliliterQuantity.Value, PicogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.PicogramPerMilliliter, picogrampermilliliterQuantity.Unit); - - var poundpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicFoot); - AssertEx.EqualTolerance(PoundsPerCubicFootInOneKilogramPerCubicMeter, (double)poundpercubicfootQuantity.Value, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, poundpercubicfootQuantity.Unit); - - var poundpercubicinchQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerCubicInch); - AssertEx.EqualTolerance(PoundsPerCubicInchInOneKilogramPerCubicMeter, (double)poundpercubicinchQuantity.Value, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, poundpercubicinchQuantity.Unit); - - var poundperimperialgallonQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerImperialGallon); - AssertEx.EqualTolerance(PoundsPerImperialGallonInOneKilogramPerCubicMeter, (double)poundperimperialgallonQuantity.Value, PoundsPerImperialGallonTolerance); - Assert.Equal(DensityUnit.PoundPerImperialGallon, poundperimperialgallonQuantity.Unit); - - var poundperusgallonQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.PoundPerUSGallon); - AssertEx.EqualTolerance(PoundsPerUSGallonInOneKilogramPerCubicMeter, (double)poundperusgallonQuantity.Value, PoundsPerUSGallonTolerance); - Assert.Equal(DensityUnit.PoundPerUSGallon, poundperusgallonQuantity.Unit); - - var slugpercubicfootQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.SlugPerCubicFoot); - AssertEx.EqualTolerance(SlugsPerCubicFootInOneKilogramPerCubicMeter, (double)slugpercubicfootQuantity.Value, SlugsPerCubicFootTolerance); - Assert.Equal(DensityUnit.SlugPerCubicFoot, slugpercubicfootQuantity.Unit); - - var tonnepercubiccentimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicCentimeter); - AssertEx.EqualTolerance(TonnesPerCubicCentimeterInOneKilogramPerCubicMeter, (double)tonnepercubiccentimeterQuantity.Value, TonnesPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicCentimeter, tonnepercubiccentimeterQuantity.Unit); - - var tonnepercubicmeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicMeter); - AssertEx.EqualTolerance(TonnesPerCubicMeterInOneKilogramPerCubicMeter, (double)tonnepercubicmeterQuantity.Value, TonnesPerCubicMeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMeter, tonnepercubicmeterQuantity.Unit); - - var tonnepercubicmillimeterQuantity = kilogrampercubicmeter.ToUnit(DensityUnit.TonnePerCubicMillimeter); - AssertEx.EqualTolerance(TonnesPerCubicMillimeterInOneKilogramPerCubicMeter, (double)tonnepercubicmillimeterQuantity.Value, TonnesPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMillimeter, tonnepercubicmillimeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerDeciLiter(kilogrampercubicmeter.CentigramsPerDeciLiter).KilogramsPerCubicMeter, CentigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerLiter(kilogrampercubicmeter.CentigramsPerLiter).KilogramsPerCubicMeter, CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerMilliliter(kilogrampercubicmeter.CentigramsPerMilliliter).KilogramsPerCubicMeter, CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerDeciLiter(kilogrampercubicmeter.DecigramsPerDeciLiter).KilogramsPerCubicMeter, DecigramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerLiter(kilogrampercubicmeter.DecigramsPerLiter).KilogramsPerCubicMeter, DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerMilliliter(kilogrampercubicmeter.DecigramsPerMilliliter).KilogramsPerCubicMeter, DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicCentimeter(kilogrampercubicmeter.GramsPerCubicCentimeter).KilogramsPerCubicMeter, GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicMeter(kilogrampercubicmeter.GramsPerCubicMeter).KilogramsPerCubicMeter, GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicMillimeter(kilogrampercubicmeter.GramsPerCubicMillimeter).KilogramsPerCubicMeter, GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerDeciLiter(kilogrampercubicmeter.GramsPerDeciLiter).KilogramsPerCubicMeter, GramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerLiter(kilogrampercubicmeter.GramsPerLiter).KilogramsPerCubicMeter, GramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerMilliliter(kilogrampercubicmeter.GramsPerMilliliter).KilogramsPerCubicMeter, GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicCentimeter(kilogrampercubicmeter.KilogramsPerCubicCentimeter).KilogramsPerCubicMeter, KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicMeter(kilogrampercubicmeter.KilogramsPerCubicMeter).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicMillimeter(kilogrampercubicmeter.KilogramsPerCubicMillimeter).KilogramsPerCubicMeter, KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilopoundsPerCubicFoot(kilogrampercubicmeter.KilopoundsPerCubicFoot).KilogramsPerCubicMeter, KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromKilopoundsPerCubicInch(kilogrampercubicmeter.KilopoundsPerCubicInch).KilogramsPerCubicMeter, KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerDeciLiter(kilogrampercubicmeter.MicrogramsPerDeciLiter).KilogramsPerCubicMeter, MicrogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerLiter(kilogrampercubicmeter.MicrogramsPerLiter).KilogramsPerCubicMeter, MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerMilliliter(kilogrampercubicmeter.MicrogramsPerMilliliter).KilogramsPerCubicMeter, MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerCubicMeter(kilogrampercubicmeter.MilligramsPerCubicMeter).KilogramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerDeciLiter(kilogrampercubicmeter.MilligramsPerDeciLiter).KilogramsPerCubicMeter, MilligramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerLiter(kilogrampercubicmeter.MilligramsPerLiter).KilogramsPerCubicMeter, MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerMilliliter(kilogrampercubicmeter.MilligramsPerMilliliter).KilogramsPerCubicMeter, MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerDeciLiter(kilogrampercubicmeter.NanogramsPerDeciLiter).KilogramsPerCubicMeter, NanogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerLiter(kilogrampercubicmeter.NanogramsPerLiter).KilogramsPerCubicMeter, NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerMilliliter(kilogrampercubicmeter.NanogramsPerMilliliter).KilogramsPerCubicMeter, NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerDeciLiter(kilogrampercubicmeter.PicogramsPerDeciLiter).KilogramsPerCubicMeter, PicogramsPerDeciLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerLiter(kilogrampercubicmeter.PicogramsPerLiter).KilogramsPerCubicMeter, PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerMilliliter(kilogrampercubicmeter.PicogramsPerMilliliter).KilogramsPerCubicMeter, PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicFoot(kilogrampercubicmeter.PoundsPerCubicFoot).KilogramsPerCubicMeter, PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicInch(kilogrampercubicmeter.PoundsPerCubicInch).KilogramsPerCubicMeter, PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerImperialGallon(kilogrampercubicmeter.PoundsPerImperialGallon).KilogramsPerCubicMeter, PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerUSGallon(kilogrampercubicmeter.PoundsPerUSGallon).KilogramsPerCubicMeter, PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicFoot(kilogrampercubicmeter.SlugsPerCubicFoot).KilogramsPerCubicMeter, SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicCentimeter(kilogrampercubicmeter.TonnesPerCubicCentimeter).KilogramsPerCubicMeter, TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicMeter(kilogrampercubicmeter.TonnesPerCubicMeter).KilogramsPerCubicMeter, TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicMillimeter(kilogrampercubicmeter.TonnesPerCubicMillimeter).KilogramsPerCubicMeter, TonnesPerCubicMillimeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Density v = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Density.FromKilogramsPerCubicMeter(3)-v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Density.FromKilogramsPerCubicMeter(10)/5).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, Density.FromKilogramsPerCubicMeter(10)/Density.FromKilogramsPerCubicMeter(5), KilogramsPerCubicMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Density oneKilogramPerCubicMeter = Density.FromKilogramsPerCubicMeter(1); - Density twoKilogramsPerCubicMeter = Density.FromKilogramsPerCubicMeter(2); - - Assert.True(oneKilogramPerCubicMeter < twoKilogramsPerCubicMeter); - Assert.True(oneKilogramPerCubicMeter <= twoKilogramsPerCubicMeter); - Assert.True(twoKilogramsPerCubicMeter > oneKilogramPerCubicMeter); - Assert.True(twoKilogramsPerCubicMeter >= oneKilogramPerCubicMeter); - - Assert.False(oneKilogramPerCubicMeter > twoKilogramsPerCubicMeter); - Assert.False(oneKilogramPerCubicMeter >= twoKilogramsPerCubicMeter); - Assert.False(twoKilogramsPerCubicMeter < oneKilogramPerCubicMeter); - Assert.False(twoKilogramsPerCubicMeter <= oneKilogramPerCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - Assert.Equal(0, kilogrampercubicmeter.CompareTo(kilogrampercubicmeter)); - Assert.True(kilogrampercubicmeter.CompareTo(Density.Zero) > 0); - Assert.True(Density.Zero.CompareTo(kilogrampercubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - Assert.Throws(() => kilogrampercubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - Assert.Throws(() => kilogrampercubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Density a = Density.FromKilogramsPerCubicMeter(1); - Density b = Density.FromKilogramsPerCubicMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Density v = Density.FromKilogramsPerCubicMeter(1); - Assert.True(v.Equals(Density.FromKilogramsPerCubicMeter(1), Density.FromKilogramsPerCubicMeter(KilogramsPerCubicMeterTolerance))); - Assert.False(v.Equals(Density.Zero, Density.FromKilogramsPerCubicMeter(KilogramsPerCubicMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - Assert.False(kilogrampercubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - Assert.False(kilogrampercubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DensityUnit.Undefined, Density.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/DurationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/DurationTestsBase.g.cs deleted file mode 100644 index 0c107c622b..0000000000 --- a/UnitsNet.Tests/GeneratedCode/DurationTestsBase.g.cs +++ /dev/null @@ -1,307 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Duration. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class DurationTestsBase - { - protected abstract double DaysInOneSecond { get; } - protected abstract double HoursInOneSecond { get; } - protected abstract double MicrosecondsInOneSecond { get; } - protected abstract double MillisecondsInOneSecond { get; } - protected abstract double MinutesInOneSecond { get; } - protected abstract double MonthsInOneSecond { get; } - protected abstract double Months30InOneSecond { get; } - protected abstract double NanosecondsInOneSecond { get; } - protected abstract double SecondsInOneSecond { get; } - protected abstract double WeeksInOneSecond { get; } - protected abstract double YearsInOneSecond { get; } - protected abstract double Years365InOneSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DaysTolerance { get { return 1e-5; } } - protected virtual double HoursTolerance { get { return 1e-5; } } - protected virtual double MicrosecondsTolerance { get { return 1e-5; } } - protected virtual double MillisecondsTolerance { get { return 1e-5; } } - protected virtual double MinutesTolerance { get { return 1e-5; } } - protected virtual double MonthsTolerance { get { return 1e-5; } } - protected virtual double Months30Tolerance { get { return 1e-5; } } - protected virtual double NanosecondsTolerance { get { return 1e-5; } } - protected virtual double SecondsTolerance { get { return 1e-5; } } - protected virtual double WeeksTolerance { get { return 1e-5; } } - protected virtual double YearsTolerance { get { return 1e-5; } } - protected virtual double Years365Tolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SecondToDurationUnits() - { - Duration second = Duration.FromSeconds(1); - AssertEx.EqualTolerance(DaysInOneSecond, second.Days, DaysTolerance); - AssertEx.EqualTolerance(HoursInOneSecond, second.Hours, HoursTolerance); - AssertEx.EqualTolerance(MicrosecondsInOneSecond, second.Microseconds, MicrosecondsTolerance); - AssertEx.EqualTolerance(MillisecondsInOneSecond, second.Milliseconds, MillisecondsTolerance); - AssertEx.EqualTolerance(MinutesInOneSecond, second.Minutes, MinutesTolerance); - AssertEx.EqualTolerance(MonthsInOneSecond, second.Months, MonthsTolerance); - AssertEx.EqualTolerance(Months30InOneSecond, second.Months30, Months30Tolerance); - AssertEx.EqualTolerance(NanosecondsInOneSecond, second.Nanoseconds, NanosecondsTolerance); - AssertEx.EqualTolerance(SecondsInOneSecond, second.Seconds, SecondsTolerance); - AssertEx.EqualTolerance(WeeksInOneSecond, second.Weeks, WeeksTolerance); - AssertEx.EqualTolerance(YearsInOneSecond, second.Years, YearsTolerance); - AssertEx.EqualTolerance(Years365InOneSecond, second.Years365, Years365Tolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Day).Days, DaysTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Hour).Hours, HoursTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Microsecond).Microseconds, MicrosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Millisecond).Milliseconds, MillisecondsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Minute).Minutes, MinutesTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Month).Months, MonthsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Month30).Months30, Months30Tolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Nanosecond).Nanoseconds, NanosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Second).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Week).Weeks, WeeksTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Year).Years, YearsTolerance); - AssertEx.EqualTolerance(1, Duration.From(1, DurationUnit.Year365).Years365, Years365Tolerance); - } - - [Fact] - public void As() - { - var second = Duration.FromSeconds(1); - AssertEx.EqualTolerance(DaysInOneSecond, second.As(DurationUnit.Day), DaysTolerance); - AssertEx.EqualTolerance(HoursInOneSecond, second.As(DurationUnit.Hour), HoursTolerance); - AssertEx.EqualTolerance(MicrosecondsInOneSecond, second.As(DurationUnit.Microsecond), MicrosecondsTolerance); - AssertEx.EqualTolerance(MillisecondsInOneSecond, second.As(DurationUnit.Millisecond), MillisecondsTolerance); - AssertEx.EqualTolerance(MinutesInOneSecond, second.As(DurationUnit.Minute), MinutesTolerance); - AssertEx.EqualTolerance(MonthsInOneSecond, second.As(DurationUnit.Month), MonthsTolerance); - AssertEx.EqualTolerance(Months30InOneSecond, second.As(DurationUnit.Month30), Months30Tolerance); - AssertEx.EqualTolerance(NanosecondsInOneSecond, second.As(DurationUnit.Nanosecond), NanosecondsTolerance); - AssertEx.EqualTolerance(SecondsInOneSecond, second.As(DurationUnit.Second), SecondsTolerance); - AssertEx.EqualTolerance(WeeksInOneSecond, second.As(DurationUnit.Week), WeeksTolerance); - AssertEx.EqualTolerance(YearsInOneSecond, second.As(DurationUnit.Year), YearsTolerance); - AssertEx.EqualTolerance(Years365InOneSecond, second.As(DurationUnit.Year365), Years365Tolerance); - } - - [Fact] - public void ToUnit() - { - var second = Duration.FromSeconds(1); - - var dayQuantity = second.ToUnit(DurationUnit.Day); - AssertEx.EqualTolerance(DaysInOneSecond, (double)dayQuantity.Value, DaysTolerance); - Assert.Equal(DurationUnit.Day, dayQuantity.Unit); - - var hourQuantity = second.ToUnit(DurationUnit.Hour); - AssertEx.EqualTolerance(HoursInOneSecond, (double)hourQuantity.Value, HoursTolerance); - Assert.Equal(DurationUnit.Hour, hourQuantity.Unit); - - var microsecondQuantity = second.ToUnit(DurationUnit.Microsecond); - AssertEx.EqualTolerance(MicrosecondsInOneSecond, (double)microsecondQuantity.Value, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, microsecondQuantity.Unit); - - var millisecondQuantity = second.ToUnit(DurationUnit.Millisecond); - AssertEx.EqualTolerance(MillisecondsInOneSecond, (double)millisecondQuantity.Value, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, millisecondQuantity.Unit); - - var minuteQuantity = second.ToUnit(DurationUnit.Minute); - AssertEx.EqualTolerance(MinutesInOneSecond, (double)minuteQuantity.Value, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, minuteQuantity.Unit); - - var monthQuantity = second.ToUnit(DurationUnit.Month); - AssertEx.EqualTolerance(MonthsInOneSecond, (double)monthQuantity.Value, MonthsTolerance); - Assert.Equal(DurationUnit.Month, monthQuantity.Unit); - - var month30Quantity = second.ToUnit(DurationUnit.Month30); - AssertEx.EqualTolerance(Months30InOneSecond, (double)month30Quantity.Value, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, month30Quantity.Unit); - - var nanosecondQuantity = second.ToUnit(DurationUnit.Nanosecond); - AssertEx.EqualTolerance(NanosecondsInOneSecond, (double)nanosecondQuantity.Value, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, nanosecondQuantity.Unit); - - var secondQuantity = second.ToUnit(DurationUnit.Second); - AssertEx.EqualTolerance(SecondsInOneSecond, (double)secondQuantity.Value, SecondsTolerance); - Assert.Equal(DurationUnit.Second, secondQuantity.Unit); - - var weekQuantity = second.ToUnit(DurationUnit.Week); - AssertEx.EqualTolerance(WeeksInOneSecond, (double)weekQuantity.Value, WeeksTolerance); - Assert.Equal(DurationUnit.Week, weekQuantity.Unit); - - var yearQuantity = second.ToUnit(DurationUnit.Year); - AssertEx.EqualTolerance(YearsInOneSecond, (double)yearQuantity.Value, YearsTolerance); - Assert.Equal(DurationUnit.Year, yearQuantity.Unit); - - var year365Quantity = second.ToUnit(DurationUnit.Year365); - AssertEx.EqualTolerance(Years365InOneSecond, (double)year365Quantity.Value, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, year365Quantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Duration second = Duration.FromSeconds(1); - AssertEx.EqualTolerance(1, Duration.FromDays(second.Days).Seconds, DaysTolerance); - AssertEx.EqualTolerance(1, Duration.FromHours(second.Hours).Seconds, HoursTolerance); - AssertEx.EqualTolerance(1, Duration.FromMicroseconds(second.Microseconds).Seconds, MicrosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMilliseconds(second.Milliseconds).Seconds, MillisecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMinutes(second.Minutes).Seconds, MinutesTolerance); - AssertEx.EqualTolerance(1, Duration.FromMonths(second.Months).Seconds, MonthsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMonths30(second.Months30).Seconds, Months30Tolerance); - AssertEx.EqualTolerance(1, Duration.FromNanoseconds(second.Nanoseconds).Seconds, NanosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromSeconds(second.Seconds).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromWeeks(second.Weeks).Seconds, WeeksTolerance); - AssertEx.EqualTolerance(1, Duration.FromYears(second.Years).Seconds, YearsTolerance); - AssertEx.EqualTolerance(1, Duration.FromYears365(second.Years365).Seconds, Years365Tolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Duration v = Duration.FromSeconds(1); - AssertEx.EqualTolerance(-1, -v.Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (Duration.FromSeconds(3)-v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (v + v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(10, (v*10).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(10, (10*v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (Duration.FromSeconds(10)/5).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, Duration.FromSeconds(10)/Duration.FromSeconds(5), SecondsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Duration oneSecond = Duration.FromSeconds(1); - Duration twoSeconds = Duration.FromSeconds(2); - - Assert.True(oneSecond < twoSeconds); - Assert.True(oneSecond <= twoSeconds); - Assert.True(twoSeconds > oneSecond); - Assert.True(twoSeconds >= oneSecond); - - Assert.False(oneSecond > twoSeconds); - Assert.False(oneSecond >= twoSeconds); - Assert.False(twoSeconds < oneSecond); - Assert.False(twoSeconds <= oneSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - Duration second = Duration.FromSeconds(1); - Assert.Equal(0, second.CompareTo(second)); - Assert.True(second.CompareTo(Duration.Zero) > 0); - Assert.True(Duration.Zero.CompareTo(second) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Duration second = Duration.FromSeconds(1); - Assert.Throws(() => second.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Duration second = Duration.FromSeconds(1); - Assert.Throws(() => second.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Duration a = Duration.FromSeconds(1); - Duration b = Duration.FromSeconds(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Duration v = Duration.FromSeconds(1); - Assert.True(v.Equals(Duration.FromSeconds(1), Duration.FromSeconds(SecondsTolerance))); - Assert.False(v.Equals(Duration.Zero, Duration.FromSeconds(SecondsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Duration second = Duration.FromSeconds(1); - Assert.False(second.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Duration second = Duration.FromSeconds(1); - Assert.False(second.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DurationUnit.Undefined, Duration.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/DynamicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/DynamicViscosityTestsBase.g.cs deleted file mode 100644 index fe80050f24..0000000000 --- a/UnitsNet.Tests/GeneratedCode/DynamicViscosityTestsBase.g.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of DynamicViscosity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class DynamicViscosityTestsBase - { - protected abstract double CentipoiseInOneNewtonSecondPerMeterSquared { get; } - protected abstract double MicropascalSecondsInOneNewtonSecondPerMeterSquared { get; } - protected abstract double MillipascalSecondsInOneNewtonSecondPerMeterSquared { get; } - protected abstract double NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared { get; } - protected abstract double PascalSecondsInOneNewtonSecondPerMeterSquared { get; } - protected abstract double PoiseInOneNewtonSecondPerMeterSquared { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentipoiseTolerance { get { return 1e-5; } } - protected virtual double MicropascalSecondsTolerance { get { return 1e-5; } } - protected virtual double MillipascalSecondsTolerance { get { return 1e-5; } } - protected virtual double NewtonSecondsPerMeterSquaredTolerance { get { return 1e-5; } } - protected virtual double PascalSecondsTolerance { get { return 1e-5; } } - protected virtual double PoiseTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonSecondPerMeterSquaredToDynamicViscosityUnits() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(CentipoiseInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.Centipoise, CentipoiseTolerance); - AssertEx.EqualTolerance(MicropascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.MicropascalSeconds, MicropascalSecondsTolerance); - AssertEx.EqualTolerance(MillipascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.MillipascalSeconds, MillipascalSecondsTolerance); - AssertEx.EqualTolerance(NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(PascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.PascalSeconds, PascalSecondsTolerance); - AssertEx.EqualTolerance(PoiseInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.Poise, PoiseTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.Centipoise).Centipoise, CentipoiseTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.MicropascalSecond).MicropascalSeconds, MicropascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.MillipascalSecond).MillipascalSeconds, MillipascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.PascalSecond).PascalSeconds, PascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.From(1, DynamicViscosityUnit.Poise).Poise, PoiseTolerance); - } - - [Fact] - public void As() - { - var newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(CentipoiseInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.Centipoise), CentipoiseTolerance); - AssertEx.EqualTolerance(MicropascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.MicropascalSecond), MicropascalSecondsTolerance); - AssertEx.EqualTolerance(MillipascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.MillipascalSecond), MillipascalSecondsTolerance); - AssertEx.EqualTolerance(NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.NewtonSecondPerMeterSquared), NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(PascalSecondsInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.PascalSecond), PascalSecondsTolerance); - AssertEx.EqualTolerance(PoiseInOneNewtonSecondPerMeterSquared, newtonsecondpermetersquared.As(DynamicViscosityUnit.Poise), PoiseTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - - var centipoiseQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.Centipoise); - AssertEx.EqualTolerance(CentipoiseInOneNewtonSecondPerMeterSquared, (double)centipoiseQuantity.Value, CentipoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Centipoise, centipoiseQuantity.Unit); - - var micropascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.MicropascalSecond); - AssertEx.EqualTolerance(MicropascalSecondsInOneNewtonSecondPerMeterSquared, (double)micropascalsecondQuantity.Value, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, micropascalsecondQuantity.Unit); - - var millipascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.MillipascalSecond); - AssertEx.EqualTolerance(MillipascalSecondsInOneNewtonSecondPerMeterSquared, (double)millipascalsecondQuantity.Value, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, millipascalsecondQuantity.Unit); - - var newtonsecondpermetersquaredQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared); - AssertEx.EqualTolerance(NewtonSecondsPerMeterSquaredInOneNewtonSecondPerMeterSquared, (double)newtonsecondpermetersquaredQuantity.Value, NewtonSecondsPerMeterSquaredTolerance); - Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, newtonsecondpermetersquaredQuantity.Unit); - - var pascalsecondQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.PascalSecond); - AssertEx.EqualTolerance(PascalSecondsInOneNewtonSecondPerMeterSquared, (double)pascalsecondQuantity.Value, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, pascalsecondQuantity.Unit); - - var poiseQuantity = newtonsecondpermetersquared.ToUnit(DynamicViscosityUnit.Poise); - AssertEx.EqualTolerance(PoiseInOneNewtonSecondPerMeterSquared, (double)poiseQuantity.Value, PoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Poise, poiseQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(1, DynamicViscosity.FromCentipoise(newtonsecondpermetersquared.Centipoise).NewtonSecondsPerMeterSquared, CentipoiseTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromMicropascalSeconds(newtonsecondpermetersquared.MicropascalSeconds).NewtonSecondsPerMeterSquared, MicropascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromMillipascalSeconds(newtonsecondpermetersquared.MillipascalSeconds).NewtonSecondsPerMeterSquared, MillipascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromNewtonSecondsPerMeterSquared(newtonsecondpermetersquared.NewtonSecondsPerMeterSquared).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPascalSeconds(newtonsecondpermetersquared.PascalSeconds).NewtonSecondsPerMeterSquared, PascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPoise(newtonsecondpermetersquared.Poise).NewtonSecondsPerMeterSquared, PoiseTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - DynamicViscosity v = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(-1, -v.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(3)-v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(10)/5).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, DynamicViscosity.FromNewtonSecondsPerMeterSquared(10)/DynamicViscosity.FromNewtonSecondsPerMeterSquared(5), NewtonSecondsPerMeterSquaredTolerance); - } - - [Fact] - public void ComparisonOperators() - { - DynamicViscosity oneNewtonSecondPerMeterSquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - DynamicViscosity twoNewtonSecondsPerMeterSquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(2); - - Assert.True(oneNewtonSecondPerMeterSquared < twoNewtonSecondsPerMeterSquared); - Assert.True(oneNewtonSecondPerMeterSquared <= twoNewtonSecondsPerMeterSquared); - Assert.True(twoNewtonSecondsPerMeterSquared > oneNewtonSecondPerMeterSquared); - Assert.True(twoNewtonSecondsPerMeterSquared >= oneNewtonSecondPerMeterSquared); - - Assert.False(oneNewtonSecondPerMeterSquared > twoNewtonSecondsPerMeterSquared); - Assert.False(oneNewtonSecondPerMeterSquared >= twoNewtonSecondsPerMeterSquared); - Assert.False(twoNewtonSecondsPerMeterSquared < oneNewtonSecondPerMeterSquared); - Assert.False(twoNewtonSecondsPerMeterSquared <= oneNewtonSecondPerMeterSquared); - } - - [Fact] - public void CompareToIsImplemented() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.Equal(0, newtonsecondpermetersquared.CompareTo(newtonsecondpermetersquared)); - Assert.True(newtonsecondpermetersquared.CompareTo(DynamicViscosity.Zero) > 0); - Assert.True(DynamicViscosity.Zero.CompareTo(newtonsecondpermetersquared) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.Throws(() => newtonsecondpermetersquared.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.Throws(() => newtonsecondpermetersquared.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - DynamicViscosity a = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - DynamicViscosity b = DynamicViscosity.FromNewtonSecondsPerMeterSquared(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - DynamicViscosity v = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.True(v.Equals(DynamicViscosity.FromNewtonSecondsPerMeterSquared(1), DynamicViscosity.FromNewtonSecondsPerMeterSquared(NewtonSecondsPerMeterSquaredTolerance))); - Assert.False(v.Equals(DynamicViscosity.Zero, DynamicViscosity.FromNewtonSecondsPerMeterSquared(NewtonSecondsPerMeterSquaredTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.False(newtonsecondpermetersquared.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.False(newtonsecondpermetersquared.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DynamicViscosityUnit.Undefined, DynamicViscosity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricAdmittanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricAdmittanceTestsBase.g.cs deleted file mode 100644 index 58097b5e01..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricAdmittanceTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricAdmittance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricAdmittanceTestsBase - { - protected abstract double MicrosiemensInOneSiemens { get; } - protected abstract double MillisiemensInOneSiemens { get; } - protected abstract double NanosiemensInOneSiemens { get; } - protected abstract double SiemensInOneSiemens { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicrosiemensTolerance { get { return 1e-5; } } - protected virtual double MillisiemensTolerance { get { return 1e-5; } } - protected virtual double NanosiemensTolerance { get { return 1e-5; } } - protected virtual double SiemensTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SiemensToElectricAdmittanceUnits() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, siemens.Microsiemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, siemens.Millisiemens, MillisiemensTolerance); - AssertEx.EqualTolerance(NanosiemensInOneSiemens, siemens.Nanosiemens, NanosiemensTolerance); - AssertEx.EqualTolerance(SiemensInOneSiemens, siemens.Siemens, SiemensTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricAdmittance.From(1, ElectricAdmittanceUnit.Microsiemens).Microsiemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.From(1, ElectricAdmittanceUnit.Millisiemens).Millisiemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.From(1, ElectricAdmittanceUnit.Nanosiemens).Nanosiemens, NanosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.From(1, ElectricAdmittanceUnit.Siemens).Siemens, SiemensTolerance); - } - - [Fact] - public void As() - { - var siemens = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, siemens.As(ElectricAdmittanceUnit.Microsiemens), MicrosiemensTolerance); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, siemens.As(ElectricAdmittanceUnit.Millisiemens), MillisiemensTolerance); - AssertEx.EqualTolerance(NanosiemensInOneSiemens, siemens.As(ElectricAdmittanceUnit.Nanosiemens), NanosiemensTolerance); - AssertEx.EqualTolerance(SiemensInOneSiemens, siemens.As(ElectricAdmittanceUnit.Siemens), SiemensTolerance); - } - - [Fact] - public void ToUnit() - { - var siemens = ElectricAdmittance.FromSiemens(1); - - var microsiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Microsiemens); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, (double)microsiemensQuantity.Value, MicrosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Microsiemens, microsiemensQuantity.Unit); - - var millisiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Millisiemens); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, (double)millisiemensQuantity.Value, MillisiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Millisiemens, millisiemensQuantity.Unit); - - var nanosiemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Nanosiemens); - AssertEx.EqualTolerance(NanosiemensInOneSiemens, (double)nanosiemensQuantity.Value, NanosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanosiemens, nanosiemensQuantity.Unit); - - var siemensQuantity = siemens.ToUnit(ElectricAdmittanceUnit.Siemens); - AssertEx.EqualTolerance(SiemensInOneSiemens, (double)siemensQuantity.Value, SiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Siemens, siemensQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMicrosiemens(siemens.Microsiemens).Siemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMillisiemens(siemens.Millisiemens).Siemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromNanosiemens(siemens.Nanosiemens).Siemens, NanosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromSiemens(siemens.Siemens).Siemens, SiemensTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricAdmittance v = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(-1, -v.Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricAdmittance.FromSiemens(3)-v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (v + v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (v*10).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (10*v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricAdmittance.FromSiemens(10)/5).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, ElectricAdmittance.FromSiemens(10)/ElectricAdmittance.FromSiemens(5), SiemensTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricAdmittance oneSiemens = ElectricAdmittance.FromSiemens(1); - ElectricAdmittance twoSiemens = ElectricAdmittance.FromSiemens(2); - - Assert.True(oneSiemens < twoSiemens); - Assert.True(oneSiemens <= twoSiemens); - Assert.True(twoSiemens > oneSiemens); - Assert.True(twoSiemens >= oneSiemens); - - Assert.False(oneSiemens > twoSiemens); - Assert.False(oneSiemens >= twoSiemens); - Assert.False(twoSiemens < oneSiemens); - Assert.False(twoSiemens <= oneSiemens); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - Assert.Equal(0, siemens.CompareTo(siemens)); - Assert.True(siemens.CompareTo(ElectricAdmittance.Zero) > 0); - Assert.True(ElectricAdmittance.Zero.CompareTo(siemens) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - Assert.Throws(() => siemens.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - Assert.Throws(() => siemens.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricAdmittance a = ElectricAdmittance.FromSiemens(1); - ElectricAdmittance b = ElectricAdmittance.FromSiemens(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricAdmittance v = ElectricAdmittance.FromSiemens(1); - Assert.True(v.Equals(ElectricAdmittance.FromSiemens(1), ElectricAdmittance.FromSiemens(SiemensTolerance))); - Assert.False(v.Equals(ElectricAdmittance.Zero, ElectricAdmittance.FromSiemens(SiemensTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - Assert.False(siemens.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - Assert.False(siemens.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricAdmittanceUnit.Undefined, ElectricAdmittance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricChargeDensityTestsBase.g.cs deleted file mode 100644 index 21589616fb..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricChargeDensityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricChargeDensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricChargeDensityTestsBase - { - protected abstract double CoulombsPerCubicMeterInOneCoulombPerCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CoulombsPerCubicMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CoulombPerCubicMeterToElectricChargeDensityUnits() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(CoulombsPerCubicMeterInOneCoulombPerCubicMeter, coulombpercubicmeter.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricChargeDensity.From(1, ElectricChargeDensityUnit.CoulombPerCubicMeter).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - } - - [Fact] - public void As() - { - var coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(CoulombsPerCubicMeterInOneCoulombPerCubicMeter, coulombpercubicmeter.As(ElectricChargeDensityUnit.CoulombPerCubicMeter), CoulombsPerCubicMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - - var coulombpercubicmeterQuantity = coulombpercubicmeter.ToUnit(ElectricChargeDensityUnit.CoulombPerCubicMeter); - AssertEx.EqualTolerance(CoulombsPerCubicMeterInOneCoulombPerCubicMeter, (double)coulombpercubicmeterQuantity.Value, CoulombsPerCubicMeterTolerance); - Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, coulombpercubicmeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(1, ElectricChargeDensity.FromCoulombsPerCubicMeter(coulombpercubicmeter.CoulombsPerCubicMeter).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricChargeDensity v = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(3)-v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(10)/5).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, ElectricChargeDensity.FromCoulombsPerCubicMeter(10)/ElectricChargeDensity.FromCoulombsPerCubicMeter(5), CoulombsPerCubicMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricChargeDensity oneCoulombPerCubicMeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - ElectricChargeDensity twoCoulombsPerCubicMeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(2); - - Assert.True(oneCoulombPerCubicMeter < twoCoulombsPerCubicMeter); - Assert.True(oneCoulombPerCubicMeter <= twoCoulombsPerCubicMeter); - Assert.True(twoCoulombsPerCubicMeter > oneCoulombPerCubicMeter); - Assert.True(twoCoulombsPerCubicMeter >= oneCoulombPerCubicMeter); - - Assert.False(oneCoulombPerCubicMeter > twoCoulombsPerCubicMeter); - Assert.False(oneCoulombPerCubicMeter >= twoCoulombsPerCubicMeter); - Assert.False(twoCoulombsPerCubicMeter < oneCoulombPerCubicMeter); - Assert.False(twoCoulombsPerCubicMeter <= oneCoulombPerCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.Equal(0, coulombpercubicmeter.CompareTo(coulombpercubicmeter)); - Assert.True(coulombpercubicmeter.CompareTo(ElectricChargeDensity.Zero) > 0); - Assert.True(ElectricChargeDensity.Zero.CompareTo(coulombpercubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.Throws(() => coulombpercubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.Throws(() => coulombpercubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricChargeDensity a = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - ElectricChargeDensity b = ElectricChargeDensity.FromCoulombsPerCubicMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricChargeDensity v = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.True(v.Equals(ElectricChargeDensity.FromCoulombsPerCubicMeter(1), ElectricChargeDensity.FromCoulombsPerCubicMeter(CoulombsPerCubicMeterTolerance))); - Assert.False(v.Equals(ElectricChargeDensity.Zero, ElectricChargeDensity.FromCoulombsPerCubicMeter(CoulombsPerCubicMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.False(coulombpercubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.False(coulombpercubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricChargeDensityUnit.Undefined, ElectricChargeDensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricChargeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricChargeTestsBase.g.cs deleted file mode 100644 index e867eb01ab..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricChargeTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricCharge. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricChargeTestsBase - { - protected abstract double CoulombsInOneCoulomb { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CoulombsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CoulombToElectricChargeUnits() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(CoulombsInOneCoulomb, coulomb.Coulombs, CoulombsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricCharge.From(1, ElectricChargeUnit.Coulomb).Coulombs, CoulombsTolerance); - } - - [Fact] - public void As() - { - var coulomb = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(CoulombsInOneCoulomb, coulomb.As(ElectricChargeUnit.Coulomb), CoulombsTolerance); - } - - [Fact] - public void ToUnit() - { - var coulomb = ElectricCharge.FromCoulombs(1); - - var coulombQuantity = coulomb.ToUnit(ElectricChargeUnit.Coulomb); - AssertEx.EqualTolerance(CoulombsInOneCoulomb, (double)coulombQuantity.Value, CoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Coulomb, coulombQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(1, ElectricCharge.FromCoulombs(coulomb.Coulombs).Coulombs, CoulombsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricCharge v = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(-1, -v.Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (ElectricCharge.FromCoulombs(3)-v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (v + v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(10, (v*10).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(10, (10*v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (ElectricCharge.FromCoulombs(10)/5).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, ElectricCharge.FromCoulombs(10)/ElectricCharge.FromCoulombs(5), CoulombsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricCharge oneCoulomb = ElectricCharge.FromCoulombs(1); - ElectricCharge twoCoulombs = ElectricCharge.FromCoulombs(2); - - Assert.True(oneCoulomb < twoCoulombs); - Assert.True(oneCoulomb <= twoCoulombs); - Assert.True(twoCoulombs > oneCoulomb); - Assert.True(twoCoulombs >= oneCoulomb); - - Assert.False(oneCoulomb > twoCoulombs); - Assert.False(oneCoulomb >= twoCoulombs); - Assert.False(twoCoulombs < oneCoulomb); - Assert.False(twoCoulombs <= oneCoulomb); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.Equal(0, coulomb.CompareTo(coulomb)); - Assert.True(coulomb.CompareTo(ElectricCharge.Zero) > 0); - Assert.True(ElectricCharge.Zero.CompareTo(coulomb) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.Throws(() => coulomb.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.Throws(() => coulomb.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricCharge a = ElectricCharge.FromCoulombs(1); - ElectricCharge b = ElectricCharge.FromCoulombs(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricCharge v = ElectricCharge.FromCoulombs(1); - Assert.True(v.Equals(ElectricCharge.FromCoulombs(1), ElectricCharge.FromCoulombs(CoulombsTolerance))); - Assert.False(v.Equals(ElectricCharge.Zero, ElectricCharge.FromCoulombs(CoulombsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.False(coulomb.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.False(coulomb.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricChargeUnit.Undefined, ElectricCharge.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricConductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricConductanceTestsBase.g.cs deleted file mode 100644 index e6e565c53f..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricConductanceTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricConductance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricConductanceTestsBase - { - protected abstract double MicrosiemensInOneSiemens { get; } - protected abstract double MillisiemensInOneSiemens { get; } - protected abstract double SiemensInOneSiemens { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicrosiemensTolerance { get { return 1e-5; } } - protected virtual double MillisiemensTolerance { get { return 1e-5; } } - protected virtual double SiemensTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SiemensToElectricConductanceUnits() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, siemens.Microsiemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, siemens.Millisiemens, MillisiemensTolerance); - AssertEx.EqualTolerance(SiemensInOneSiemens, siemens.Siemens, SiemensTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricConductance.From(1, ElectricConductanceUnit.Microsiemens).Microsiemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.From(1, ElectricConductanceUnit.Millisiemens).Millisiemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.From(1, ElectricConductanceUnit.Siemens).Siemens, SiemensTolerance); - } - - [Fact] - public void As() - { - var siemens = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, siemens.As(ElectricConductanceUnit.Microsiemens), MicrosiemensTolerance); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, siemens.As(ElectricConductanceUnit.Millisiemens), MillisiemensTolerance); - AssertEx.EqualTolerance(SiemensInOneSiemens, siemens.As(ElectricConductanceUnit.Siemens), SiemensTolerance); - } - - [Fact] - public void ToUnit() - { - var siemens = ElectricConductance.FromSiemens(1); - - var microsiemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Microsiemens); - AssertEx.EqualTolerance(MicrosiemensInOneSiemens, (double)microsiemensQuantity.Value, MicrosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Microsiemens, microsiemensQuantity.Unit); - - var millisiemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Millisiemens); - AssertEx.EqualTolerance(MillisiemensInOneSiemens, (double)millisiemensQuantity.Value, MillisiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Millisiemens, millisiemensQuantity.Unit); - - var siemensQuantity = siemens.ToUnit(ElectricConductanceUnit.Siemens); - AssertEx.EqualTolerance(SiemensInOneSiemens, (double)siemensQuantity.Value, SiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Siemens, siemensQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(1, ElectricConductance.FromMicrosiemens(siemens.Microsiemens).Siemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMillisiemens(siemens.Millisiemens).Siemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromSiemens(siemens.Siemens).Siemens, SiemensTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricConductance v = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(-1, -v.Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricConductance.FromSiemens(3)-v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (v + v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (v*10).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (10*v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricConductance.FromSiemens(10)/5).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, ElectricConductance.FromSiemens(10)/ElectricConductance.FromSiemens(5), SiemensTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricConductance oneSiemens = ElectricConductance.FromSiemens(1); - ElectricConductance twoSiemens = ElectricConductance.FromSiemens(2); - - Assert.True(oneSiemens < twoSiemens); - Assert.True(oneSiemens <= twoSiemens); - Assert.True(twoSiemens > oneSiemens); - Assert.True(twoSiemens >= oneSiemens); - - Assert.False(oneSiemens > twoSiemens); - Assert.False(oneSiemens >= twoSiemens); - Assert.False(twoSiemens < oneSiemens); - Assert.False(twoSiemens <= oneSiemens); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - Assert.Equal(0, siemens.CompareTo(siemens)); - Assert.True(siemens.CompareTo(ElectricConductance.Zero) > 0); - Assert.True(ElectricConductance.Zero.CompareTo(siemens) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - Assert.Throws(() => siemens.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - Assert.Throws(() => siemens.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricConductance a = ElectricConductance.FromSiemens(1); - ElectricConductance b = ElectricConductance.FromSiemens(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricConductance v = ElectricConductance.FromSiemens(1); - Assert.True(v.Equals(ElectricConductance.FromSiemens(1), ElectricConductance.FromSiemens(SiemensTolerance))); - Assert.False(v.Equals(ElectricConductance.Zero, ElectricConductance.FromSiemens(SiemensTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - Assert.False(siemens.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - Assert.False(siemens.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricConductanceUnit.Undefined, ElectricConductance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricConductivityTestsBase.g.cs deleted file mode 100644 index afa9552ae4..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricConductivityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricConductivity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricConductivityTestsBase - { - protected abstract double SiemensPerMeterInOneSiemensPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double SiemensPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SiemensPerMeterToElectricConductivityUnits() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(SiemensPerMeterInOneSiemensPerMeter, siemenspermeter.SiemensPerMeter, SiemensPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricConductivity.From(1, ElectricConductivityUnit.SiemensPerMeter).SiemensPerMeter, SiemensPerMeterTolerance); - } - - [Fact] - public void As() - { - var siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(SiemensPerMeterInOneSiemensPerMeter, siemenspermeter.As(ElectricConductivityUnit.SiemensPerMeter), SiemensPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - - var siemenspermeterQuantity = siemenspermeter.ToUnit(ElectricConductivityUnit.SiemensPerMeter); - AssertEx.EqualTolerance(SiemensPerMeterInOneSiemensPerMeter, (double)siemenspermeterQuantity.Value, SiemensPerMeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, siemenspermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(1, ElectricConductivity.FromSiemensPerMeter(siemenspermeter.SiemensPerMeter).SiemensPerMeter, SiemensPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricConductivity v = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(-1, -v.SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricConductivity.FromSiemensPerMeter(3)-v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricConductivity.FromSiemensPerMeter(10)/5).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, ElectricConductivity.FromSiemensPerMeter(10)/ElectricConductivity.FromSiemensPerMeter(5), SiemensPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricConductivity oneSiemensPerMeter = ElectricConductivity.FromSiemensPerMeter(1); - ElectricConductivity twoSiemensPerMeter = ElectricConductivity.FromSiemensPerMeter(2); - - Assert.True(oneSiemensPerMeter < twoSiemensPerMeter); - Assert.True(oneSiemensPerMeter <= twoSiemensPerMeter); - Assert.True(twoSiemensPerMeter > oneSiemensPerMeter); - Assert.True(twoSiemensPerMeter >= oneSiemensPerMeter); - - Assert.False(oneSiemensPerMeter > twoSiemensPerMeter); - Assert.False(oneSiemensPerMeter >= twoSiemensPerMeter); - Assert.False(twoSiemensPerMeter < oneSiemensPerMeter); - Assert.False(twoSiemensPerMeter <= oneSiemensPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.Equal(0, siemenspermeter.CompareTo(siemenspermeter)); - Assert.True(siemenspermeter.CompareTo(ElectricConductivity.Zero) > 0); - Assert.True(ElectricConductivity.Zero.CompareTo(siemenspermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.Throws(() => siemenspermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.Throws(() => siemenspermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricConductivity a = ElectricConductivity.FromSiemensPerMeter(1); - ElectricConductivity b = ElectricConductivity.FromSiemensPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricConductivity v = ElectricConductivity.FromSiemensPerMeter(1); - Assert.True(v.Equals(ElectricConductivity.FromSiemensPerMeter(1), ElectricConductivity.FromSiemensPerMeter(SiemensPerMeterTolerance))); - Assert.False(v.Equals(ElectricConductivity.Zero, ElectricConductivity.FromSiemensPerMeter(SiemensPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.False(siemenspermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.False(siemenspermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricConductivityUnit.Undefined, ElectricConductivity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricCurrentDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricCurrentDensityTestsBase.g.cs deleted file mode 100644 index 4f28d50282..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricCurrentDensityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricCurrentDensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricCurrentDensityTestsBase - { - protected abstract double AmperesPerSquareMeterInOneAmperePerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void AmperePerSquareMeterToElectricCurrentDensityUnits() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(AmperesPerSquareMeterInOneAmperePerSquareMeter, amperepersquaremeter.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricCurrentDensity.From(1, ElectricCurrentDensityUnit.AmperePerSquareMeter).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(AmperesPerSquareMeterInOneAmperePerSquareMeter, amperepersquaremeter.As(ElectricCurrentDensityUnit.AmperePerSquareMeter), AmperesPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - - var amperepersquaremeterQuantity = amperepersquaremeter.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter); - AssertEx.EqualTolerance(AmperesPerSquareMeterInOneAmperePerSquareMeter, (double)amperepersquaremeterQuantity.Value, AmperesPerSquareMeterTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, amperepersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(1, ElectricCurrentDensity.FromAmperesPerSquareMeter(amperepersquaremeter.AmperesPerSquareMeter).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricCurrentDensity v = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(3)-v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(10)/5).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, ElectricCurrentDensity.FromAmperesPerSquareMeter(10)/ElectricCurrentDensity.FromAmperesPerSquareMeter(5), AmperesPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricCurrentDensity oneAmperePerSquareMeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - ElectricCurrentDensity twoAmperesPerSquareMeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(2); - - Assert.True(oneAmperePerSquareMeter < twoAmperesPerSquareMeter); - Assert.True(oneAmperePerSquareMeter <= twoAmperesPerSquareMeter); - Assert.True(twoAmperesPerSquareMeter > oneAmperePerSquareMeter); - Assert.True(twoAmperesPerSquareMeter >= oneAmperePerSquareMeter); - - Assert.False(oneAmperePerSquareMeter > twoAmperesPerSquareMeter); - Assert.False(oneAmperePerSquareMeter >= twoAmperesPerSquareMeter); - Assert.False(twoAmperesPerSquareMeter < oneAmperePerSquareMeter); - Assert.False(twoAmperesPerSquareMeter <= oneAmperePerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.Equal(0, amperepersquaremeter.CompareTo(amperepersquaremeter)); - Assert.True(amperepersquaremeter.CompareTo(ElectricCurrentDensity.Zero) > 0); - Assert.True(ElectricCurrentDensity.Zero.CompareTo(amperepersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.Throws(() => amperepersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.Throws(() => amperepersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricCurrentDensity a = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - ElectricCurrentDensity b = ElectricCurrentDensity.FromAmperesPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricCurrentDensity v = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.True(v.Equals(ElectricCurrentDensity.FromAmperesPerSquareMeter(1), ElectricCurrentDensity.FromAmperesPerSquareMeter(AmperesPerSquareMeterTolerance))); - Assert.False(v.Equals(ElectricCurrentDensity.Zero, ElectricCurrentDensity.FromAmperesPerSquareMeter(AmperesPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.False(amperepersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.False(amperepersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentDensityUnit.Undefined, ElectricCurrentDensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricCurrentGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricCurrentGradientTestsBase.g.cs deleted file mode 100644 index 066f847fa9..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricCurrentGradientTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricCurrentGradient. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricCurrentGradientTestsBase - { - protected abstract double AmperesPerSecondInOneAmperePerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void AmperePerSecondToElectricCurrentGradientUnits() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(AmperesPerSecondInOneAmperePerSecond, amperepersecond.AmperesPerSecond, AmperesPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerSecond).AmperesPerSecond, AmperesPerSecondTolerance); - } - - [Fact] - public void As() - { - var amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(AmperesPerSecondInOneAmperePerSecond, amperepersecond.As(ElectricCurrentGradientUnit.AmperePerSecond), AmperesPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - - var amperepersecondQuantity = amperepersecond.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond); - AssertEx.EqualTolerance(AmperesPerSecondInOneAmperePerSecond, (double)amperepersecondQuantity.Value, AmperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, amperepersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerSecond(amperepersecond.AmperesPerSecond).AmperesPerSecond, AmperesPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricCurrentGradient v = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentGradient.FromAmperesPerSecond(3)-v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentGradient.FromAmperesPerSecond(10)/5).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, ElectricCurrentGradient.FromAmperesPerSecond(10)/ElectricCurrentGradient.FromAmperesPerSecond(5), AmperesPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricCurrentGradient oneAmperePerSecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - ElectricCurrentGradient twoAmperesPerSecond = ElectricCurrentGradient.FromAmperesPerSecond(2); - - Assert.True(oneAmperePerSecond < twoAmperesPerSecond); - Assert.True(oneAmperePerSecond <= twoAmperesPerSecond); - Assert.True(twoAmperesPerSecond > oneAmperePerSecond); - Assert.True(twoAmperesPerSecond >= oneAmperePerSecond); - - Assert.False(oneAmperePerSecond > twoAmperesPerSecond); - Assert.False(oneAmperePerSecond >= twoAmperesPerSecond); - Assert.False(twoAmperesPerSecond < oneAmperePerSecond); - Assert.False(twoAmperesPerSecond <= oneAmperePerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.Equal(0, amperepersecond.CompareTo(amperepersecond)); - Assert.True(amperepersecond.CompareTo(ElectricCurrentGradient.Zero) > 0); - Assert.True(ElectricCurrentGradient.Zero.CompareTo(amperepersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.Throws(() => amperepersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.Throws(() => amperepersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricCurrentGradient a = ElectricCurrentGradient.FromAmperesPerSecond(1); - ElectricCurrentGradient b = ElectricCurrentGradient.FromAmperesPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricCurrentGradient v = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.True(v.Equals(ElectricCurrentGradient.FromAmperesPerSecond(1), ElectricCurrentGradient.FromAmperesPerSecond(AmperesPerSecondTolerance))); - Assert.False(v.Equals(ElectricCurrentGradient.Zero, ElectricCurrentGradient.FromAmperesPerSecond(AmperesPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.False(amperepersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.False(amperepersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentGradientUnit.Undefined, ElectricCurrentGradient.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricCurrentTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricCurrentTestsBase.g.cs deleted file mode 100644 index 44e66c1490..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricCurrentTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricCurrent. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricCurrentTestsBase - { - protected abstract double AmperesInOneAmpere { get; } - protected abstract double CentiamperesInOneAmpere { get; } - protected abstract double KiloamperesInOneAmpere { get; } - protected abstract double MegaamperesInOneAmpere { get; } - protected abstract double MicroamperesInOneAmpere { get; } - protected abstract double MilliamperesInOneAmpere { get; } - protected abstract double NanoamperesInOneAmpere { get; } - protected abstract double PicoamperesInOneAmpere { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesTolerance { get { return 1e-5; } } - protected virtual double CentiamperesTolerance { get { return 1e-5; } } - protected virtual double KiloamperesTolerance { get { return 1e-5; } } - protected virtual double MegaamperesTolerance { get { return 1e-5; } } - protected virtual double MicroamperesTolerance { get { return 1e-5; } } - protected virtual double MilliamperesTolerance { get { return 1e-5; } } - protected virtual double NanoamperesTolerance { get { return 1e-5; } } - protected virtual double PicoamperesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void AmpereToElectricCurrentUnits() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(AmperesInOneAmpere, ampere.Amperes, AmperesTolerance); - AssertEx.EqualTolerance(CentiamperesInOneAmpere, ampere.Centiamperes, CentiamperesTolerance); - AssertEx.EqualTolerance(KiloamperesInOneAmpere, ampere.Kiloamperes, KiloamperesTolerance); - AssertEx.EqualTolerance(MegaamperesInOneAmpere, ampere.Megaamperes, MegaamperesTolerance); - AssertEx.EqualTolerance(MicroamperesInOneAmpere, ampere.Microamperes, MicroamperesTolerance); - AssertEx.EqualTolerance(MilliamperesInOneAmpere, ampere.Milliamperes, MilliamperesTolerance); - AssertEx.EqualTolerance(NanoamperesInOneAmpere, ampere.Nanoamperes, NanoamperesTolerance); - AssertEx.EqualTolerance(PicoamperesInOneAmpere, ampere.Picoamperes, PicoamperesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Ampere).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Centiampere).Centiamperes, CentiamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Kiloampere).Kiloamperes, KiloamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Megaampere).Megaamperes, MegaamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Microampere).Microamperes, MicroamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Milliampere).Milliamperes, MilliamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Nanoampere).Nanoamperes, NanoamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.From(1, ElectricCurrentUnit.Picoampere).Picoamperes, PicoamperesTolerance); - } - - [Fact] - public void As() - { - var ampere = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(AmperesInOneAmpere, ampere.As(ElectricCurrentUnit.Ampere), AmperesTolerance); - AssertEx.EqualTolerance(CentiamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Centiampere), CentiamperesTolerance); - AssertEx.EqualTolerance(KiloamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Kiloampere), KiloamperesTolerance); - AssertEx.EqualTolerance(MegaamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Megaampere), MegaamperesTolerance); - AssertEx.EqualTolerance(MicroamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Microampere), MicroamperesTolerance); - AssertEx.EqualTolerance(MilliamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Milliampere), MilliamperesTolerance); - AssertEx.EqualTolerance(NanoamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Nanoampere), NanoamperesTolerance); - AssertEx.EqualTolerance(PicoamperesInOneAmpere, ampere.As(ElectricCurrentUnit.Picoampere), PicoamperesTolerance); - } - - [Fact] - public void ToUnit() - { - var ampere = ElectricCurrent.FromAmperes(1); - - var ampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Ampere); - AssertEx.EqualTolerance(AmperesInOneAmpere, (double)ampereQuantity.Value, AmperesTolerance); - Assert.Equal(ElectricCurrentUnit.Ampere, ampereQuantity.Unit); - - var centiampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Centiampere); - AssertEx.EqualTolerance(CentiamperesInOneAmpere, (double)centiampereQuantity.Value, CentiamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Centiampere, centiampereQuantity.Unit); - - var kiloampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Kiloampere); - AssertEx.EqualTolerance(KiloamperesInOneAmpere, (double)kiloampereQuantity.Value, KiloamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Kiloampere, kiloampereQuantity.Unit); - - var megaampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Megaampere); - AssertEx.EqualTolerance(MegaamperesInOneAmpere, (double)megaampereQuantity.Value, MegaamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Megaampere, megaampereQuantity.Unit); - - var microampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Microampere); - AssertEx.EqualTolerance(MicroamperesInOneAmpere, (double)microampereQuantity.Value, MicroamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Microampere, microampereQuantity.Unit); - - var milliampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Milliampere); - AssertEx.EqualTolerance(MilliamperesInOneAmpere, (double)milliampereQuantity.Value, MilliamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Milliampere, milliampereQuantity.Unit); - - var nanoampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Nanoampere); - AssertEx.EqualTolerance(NanoamperesInOneAmpere, (double)nanoampereQuantity.Value, NanoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Nanoampere, nanoampereQuantity.Unit); - - var picoampereQuantity = ampere.ToUnit(ElectricCurrentUnit.Picoampere); - AssertEx.EqualTolerance(PicoamperesInOneAmpere, (double)picoampereQuantity.Value, PicoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Picoampere, picoampereQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(1, ElectricCurrent.FromAmperes(ampere.Amperes).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromCentiamperes(ampere.Centiamperes).Amperes, CentiamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromKiloamperes(ampere.Kiloamperes).Amperes, KiloamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMegaamperes(ampere.Megaamperes).Amperes, MegaamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMicroamperes(ampere.Microamperes).Amperes, MicroamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMilliamperes(ampere.Milliamperes).Amperes, MilliamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromNanoamperes(ampere.Nanoamperes).Amperes, NanoamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromPicoamperes(ampere.Picoamperes).Amperes, PicoamperesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricCurrent v = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(-1, -v.Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrent.FromAmperes(3)-v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (v + v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(10, (v*10).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(10, (10*v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrent.FromAmperes(10)/5).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, ElectricCurrent.FromAmperes(10)/ElectricCurrent.FromAmperes(5), AmperesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricCurrent oneAmpere = ElectricCurrent.FromAmperes(1); - ElectricCurrent twoAmperes = ElectricCurrent.FromAmperes(2); - - Assert.True(oneAmpere < twoAmperes); - Assert.True(oneAmpere <= twoAmperes); - Assert.True(twoAmperes > oneAmpere); - Assert.True(twoAmperes >= oneAmpere); - - Assert.False(oneAmpere > twoAmperes); - Assert.False(oneAmpere >= twoAmperes); - Assert.False(twoAmperes < oneAmpere); - Assert.False(twoAmperes <= oneAmpere); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.Equal(0, ampere.CompareTo(ampere)); - Assert.True(ampere.CompareTo(ElectricCurrent.Zero) > 0); - Assert.True(ElectricCurrent.Zero.CompareTo(ampere) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.Throws(() => ampere.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.Throws(() => ampere.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricCurrent a = ElectricCurrent.FromAmperes(1); - ElectricCurrent b = ElectricCurrent.FromAmperes(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricCurrent v = ElectricCurrent.FromAmperes(1); - Assert.True(v.Equals(ElectricCurrent.FromAmperes(1), ElectricCurrent.FromAmperes(AmperesTolerance))); - Assert.False(v.Equals(ElectricCurrent.Zero, ElectricCurrent.FromAmperes(AmperesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.False(ampere.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.False(ampere.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentUnit.Undefined, ElectricCurrent.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricFieldTestsBase.g.cs deleted file mode 100644 index 559f971e51..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricFieldTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricField. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricFieldTestsBase - { - protected abstract double VoltsPerMeterInOneVoltPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double VoltsPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltPerMeterToElectricFieldUnits() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(VoltsPerMeterInOneVoltPerMeter, voltpermeter.VoltsPerMeter, VoltsPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricField.From(1, ElectricFieldUnit.VoltPerMeter).VoltsPerMeter, VoltsPerMeterTolerance); - } - - [Fact] - public void As() - { - var voltpermeter = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(VoltsPerMeterInOneVoltPerMeter, voltpermeter.As(ElectricFieldUnit.VoltPerMeter), VoltsPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var voltpermeter = ElectricField.FromVoltsPerMeter(1); - - var voltpermeterQuantity = voltpermeter.ToUnit(ElectricFieldUnit.VoltPerMeter); - AssertEx.EqualTolerance(VoltsPerMeterInOneVoltPerMeter, (double)voltpermeterQuantity.Value, VoltsPerMeterTolerance); - Assert.Equal(ElectricFieldUnit.VoltPerMeter, voltpermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(1, ElectricField.FromVoltsPerMeter(voltpermeter.VoltsPerMeter).VoltsPerMeter, VoltsPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricField v = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricField.FromVoltsPerMeter(3)-v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricField.FromVoltsPerMeter(10)/5).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, ElectricField.FromVoltsPerMeter(10)/ElectricField.FromVoltsPerMeter(5), VoltsPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricField oneVoltPerMeter = ElectricField.FromVoltsPerMeter(1); - ElectricField twoVoltsPerMeter = ElectricField.FromVoltsPerMeter(2); - - Assert.True(oneVoltPerMeter < twoVoltsPerMeter); - Assert.True(oneVoltPerMeter <= twoVoltsPerMeter); - Assert.True(twoVoltsPerMeter > oneVoltPerMeter); - Assert.True(twoVoltsPerMeter >= oneVoltPerMeter); - - Assert.False(oneVoltPerMeter > twoVoltsPerMeter); - Assert.False(oneVoltPerMeter >= twoVoltsPerMeter); - Assert.False(twoVoltsPerMeter < oneVoltPerMeter); - Assert.False(twoVoltsPerMeter <= oneVoltPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.Equal(0, voltpermeter.CompareTo(voltpermeter)); - Assert.True(voltpermeter.CompareTo(ElectricField.Zero) > 0); - Assert.True(ElectricField.Zero.CompareTo(voltpermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.Throws(() => voltpermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.Throws(() => voltpermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricField a = ElectricField.FromVoltsPerMeter(1); - ElectricField b = ElectricField.FromVoltsPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricField v = ElectricField.FromVoltsPerMeter(1); - Assert.True(v.Equals(ElectricField.FromVoltsPerMeter(1), ElectricField.FromVoltsPerMeter(VoltsPerMeterTolerance))); - Assert.False(v.Equals(ElectricField.Zero, ElectricField.FromVoltsPerMeter(VoltsPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.False(voltpermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.False(voltpermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricFieldUnit.Undefined, ElectricField.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricInductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricInductanceTestsBase.g.cs deleted file mode 100644 index 365c500dc2..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricInductanceTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricInductance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricInductanceTestsBase - { - protected abstract double HenriesInOneHenry { get; } - protected abstract double MicrohenriesInOneHenry { get; } - protected abstract double MillihenriesInOneHenry { get; } - protected abstract double NanohenriesInOneHenry { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HenriesTolerance { get { return 1e-5; } } - protected virtual double MicrohenriesTolerance { get { return 1e-5; } } - protected virtual double MillihenriesTolerance { get { return 1e-5; } } - protected virtual double NanohenriesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void HenryToElectricInductanceUnits() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(HenriesInOneHenry, henry.Henries, HenriesTolerance); - AssertEx.EqualTolerance(MicrohenriesInOneHenry, henry.Microhenries, MicrohenriesTolerance); - AssertEx.EqualTolerance(MillihenriesInOneHenry, henry.Millihenries, MillihenriesTolerance); - AssertEx.EqualTolerance(NanohenriesInOneHenry, henry.Nanohenries, NanohenriesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricInductance.From(1, ElectricInductanceUnit.Henry).Henries, HenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.From(1, ElectricInductanceUnit.Microhenry).Microhenries, MicrohenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.From(1, ElectricInductanceUnit.Millihenry).Millihenries, MillihenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.From(1, ElectricInductanceUnit.Nanohenry).Nanohenries, NanohenriesTolerance); - } - - [Fact] - public void As() - { - var henry = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(HenriesInOneHenry, henry.As(ElectricInductanceUnit.Henry), HenriesTolerance); - AssertEx.EqualTolerance(MicrohenriesInOneHenry, henry.As(ElectricInductanceUnit.Microhenry), MicrohenriesTolerance); - AssertEx.EqualTolerance(MillihenriesInOneHenry, henry.As(ElectricInductanceUnit.Millihenry), MillihenriesTolerance); - AssertEx.EqualTolerance(NanohenriesInOneHenry, henry.As(ElectricInductanceUnit.Nanohenry), NanohenriesTolerance); - } - - [Fact] - public void ToUnit() - { - var henry = ElectricInductance.FromHenries(1); - - var henryQuantity = henry.ToUnit(ElectricInductanceUnit.Henry); - AssertEx.EqualTolerance(HenriesInOneHenry, (double)henryQuantity.Value, HenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Henry, henryQuantity.Unit); - - var microhenryQuantity = henry.ToUnit(ElectricInductanceUnit.Microhenry); - AssertEx.EqualTolerance(MicrohenriesInOneHenry, (double)microhenryQuantity.Value, MicrohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Microhenry, microhenryQuantity.Unit); - - var millihenryQuantity = henry.ToUnit(ElectricInductanceUnit.Millihenry); - AssertEx.EqualTolerance(MillihenriesInOneHenry, (double)millihenryQuantity.Value, MillihenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Millihenry, millihenryQuantity.Unit); - - var nanohenryQuantity = henry.ToUnit(ElectricInductanceUnit.Nanohenry); - AssertEx.EqualTolerance(NanohenriesInOneHenry, (double)nanohenryQuantity.Value, NanohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Nanohenry, nanohenryQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(1, ElectricInductance.FromHenries(henry.Henries).Henries, HenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromMicrohenries(henry.Microhenries).Henries, MicrohenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromMillihenries(henry.Millihenries).Henries, MillihenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromNanohenries(henry.Nanohenries).Henries, NanohenriesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricInductance v = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(-1, -v.Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (ElectricInductance.FromHenries(3)-v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (v + v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(10, (v*10).Henries, HenriesTolerance); - AssertEx.EqualTolerance(10, (10*v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (ElectricInductance.FromHenries(10)/5).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, ElectricInductance.FromHenries(10)/ElectricInductance.FromHenries(5), HenriesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricInductance oneHenry = ElectricInductance.FromHenries(1); - ElectricInductance twoHenries = ElectricInductance.FromHenries(2); - - Assert.True(oneHenry < twoHenries); - Assert.True(oneHenry <= twoHenries); - Assert.True(twoHenries > oneHenry); - Assert.True(twoHenries >= oneHenry); - - Assert.False(oneHenry > twoHenries); - Assert.False(oneHenry >= twoHenries); - Assert.False(twoHenries < oneHenry); - Assert.False(twoHenries <= oneHenry); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.Equal(0, henry.CompareTo(henry)); - Assert.True(henry.CompareTo(ElectricInductance.Zero) > 0); - Assert.True(ElectricInductance.Zero.CompareTo(henry) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.Throws(() => henry.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.Throws(() => henry.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricInductance a = ElectricInductance.FromHenries(1); - ElectricInductance b = ElectricInductance.FromHenries(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricInductance v = ElectricInductance.FromHenries(1); - Assert.True(v.Equals(ElectricInductance.FromHenries(1), ElectricInductance.FromHenries(HenriesTolerance))); - Assert.False(v.Equals(ElectricInductance.Zero, ElectricInductance.FromHenries(HenriesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.False(henry.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.False(henry.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricInductanceUnit.Undefined, ElectricInductance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricPotentialAcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricPotentialAcTestsBase.g.cs deleted file mode 100644 index 382dca9c20..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricPotentialAcTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricPotentialAc. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricPotentialAcTestsBase - { - protected abstract double KilovoltsAcInOneVoltAc { get; } - protected abstract double MegavoltsAcInOneVoltAc { get; } - protected abstract double MicrovoltsAcInOneVoltAc { get; } - protected abstract double MillivoltsAcInOneVoltAc { get; } - protected abstract double VoltsAcInOneVoltAc { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsAcTolerance { get { return 1e-5; } } - protected virtual double MegavoltsAcTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsAcTolerance { get { return 1e-5; } } - protected virtual double MillivoltsAcTolerance { get { return 1e-5; } } - protected virtual double VoltsAcTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltAcToElectricPotentialAcUnits() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - AssertEx.EqualTolerance(KilovoltsAcInOneVoltAc, voltac.KilovoltsAc, KilovoltsAcTolerance); - AssertEx.EqualTolerance(MegavoltsAcInOneVoltAc, voltac.MegavoltsAc, MegavoltsAcTolerance); - AssertEx.EqualTolerance(MicrovoltsAcInOneVoltAc, voltac.MicrovoltsAc, MicrovoltsAcTolerance); - AssertEx.EqualTolerance(MillivoltsAcInOneVoltAc, voltac.MillivoltsAc, MillivoltsAcTolerance); - AssertEx.EqualTolerance(VoltsAcInOneVoltAc, voltac.VoltsAc, VoltsAcTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricPotentialAc.From(1, ElectricPotentialAcUnit.KilovoltAc).KilovoltsAc, KilovoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.From(1, ElectricPotentialAcUnit.MegavoltAc).MegavoltsAc, MegavoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.From(1, ElectricPotentialAcUnit.MicrovoltAc).MicrovoltsAc, MicrovoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.From(1, ElectricPotentialAcUnit.MillivoltAc).MillivoltsAc, MillivoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.From(1, ElectricPotentialAcUnit.VoltAc).VoltsAc, VoltsAcTolerance); - } - - [Fact] - public void As() - { - var voltac = ElectricPotentialAc.FromVoltsAc(1); - AssertEx.EqualTolerance(KilovoltsAcInOneVoltAc, voltac.As(ElectricPotentialAcUnit.KilovoltAc), KilovoltsAcTolerance); - AssertEx.EqualTolerance(MegavoltsAcInOneVoltAc, voltac.As(ElectricPotentialAcUnit.MegavoltAc), MegavoltsAcTolerance); - AssertEx.EqualTolerance(MicrovoltsAcInOneVoltAc, voltac.As(ElectricPotentialAcUnit.MicrovoltAc), MicrovoltsAcTolerance); - AssertEx.EqualTolerance(MillivoltsAcInOneVoltAc, voltac.As(ElectricPotentialAcUnit.MillivoltAc), MillivoltsAcTolerance); - AssertEx.EqualTolerance(VoltsAcInOneVoltAc, voltac.As(ElectricPotentialAcUnit.VoltAc), VoltsAcTolerance); - } - - [Fact] - public void ToUnit() - { - var voltac = ElectricPotentialAc.FromVoltsAc(1); - - var kilovoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.KilovoltAc); - AssertEx.EqualTolerance(KilovoltsAcInOneVoltAc, (double)kilovoltacQuantity.Value, KilovoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.KilovoltAc, kilovoltacQuantity.Unit); - - var megavoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MegavoltAc); - AssertEx.EqualTolerance(MegavoltsAcInOneVoltAc, (double)megavoltacQuantity.Value, MegavoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MegavoltAc, megavoltacQuantity.Unit); - - var microvoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MicrovoltAc); - AssertEx.EqualTolerance(MicrovoltsAcInOneVoltAc, (double)microvoltacQuantity.Value, MicrovoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MicrovoltAc, microvoltacQuantity.Unit); - - var millivoltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.MillivoltAc); - AssertEx.EqualTolerance(MillivoltsAcInOneVoltAc, (double)millivoltacQuantity.Value, MillivoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.MillivoltAc, millivoltacQuantity.Unit); - - var voltacQuantity = voltac.ToUnit(ElectricPotentialAcUnit.VoltAc); - AssertEx.EqualTolerance(VoltsAcInOneVoltAc, (double)voltacQuantity.Value, VoltsAcTolerance); - Assert.Equal(ElectricPotentialAcUnit.VoltAc, voltacQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - AssertEx.EqualTolerance(1, ElectricPotentialAc.FromKilovoltsAc(voltac.KilovoltsAc).VoltsAc, KilovoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.FromMegavoltsAc(voltac.MegavoltsAc).VoltsAc, MegavoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.FromMicrovoltsAc(voltac.MicrovoltsAc).VoltsAc, MicrovoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.FromMillivoltsAc(voltac.MillivoltsAc).VoltsAc, MillivoltsAcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialAc.FromVoltsAc(voltac.VoltsAc).VoltsAc, VoltsAcTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricPotentialAc v = ElectricPotentialAc.FromVoltsAc(1); - AssertEx.EqualTolerance(-1, -v.VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialAc.FromVoltsAc(3)-v).VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialAc.FromVoltsAc(10)/5).VoltsAc, VoltsAcTolerance); - AssertEx.EqualTolerance(2, ElectricPotentialAc.FromVoltsAc(10)/ElectricPotentialAc.FromVoltsAc(5), VoltsAcTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricPotentialAc oneVoltAc = ElectricPotentialAc.FromVoltsAc(1); - ElectricPotentialAc twoVoltsAc = ElectricPotentialAc.FromVoltsAc(2); - - Assert.True(oneVoltAc < twoVoltsAc); - Assert.True(oneVoltAc <= twoVoltsAc); - Assert.True(twoVoltsAc > oneVoltAc); - Assert.True(twoVoltsAc >= oneVoltAc); - - Assert.False(oneVoltAc > twoVoltsAc); - Assert.False(oneVoltAc >= twoVoltsAc); - Assert.False(twoVoltsAc < oneVoltAc); - Assert.False(twoVoltsAc <= oneVoltAc); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - Assert.Equal(0, voltac.CompareTo(voltac)); - Assert.True(voltac.CompareTo(ElectricPotentialAc.Zero) > 0); - Assert.True(ElectricPotentialAc.Zero.CompareTo(voltac) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - Assert.Throws(() => voltac.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - Assert.Throws(() => voltac.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricPotentialAc a = ElectricPotentialAc.FromVoltsAc(1); - ElectricPotentialAc b = ElectricPotentialAc.FromVoltsAc(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricPotentialAc v = ElectricPotentialAc.FromVoltsAc(1); - Assert.True(v.Equals(ElectricPotentialAc.FromVoltsAc(1), ElectricPotentialAc.FromVoltsAc(VoltsAcTolerance))); - Assert.False(v.Equals(ElectricPotentialAc.Zero, ElectricPotentialAc.FromVoltsAc(VoltsAcTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - Assert.False(voltac.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricPotentialAc voltac = ElectricPotentialAc.FromVoltsAc(1); - Assert.False(voltac.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialAcUnit.Undefined, ElectricPotentialAc.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricPotentialDcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricPotentialDcTestsBase.g.cs deleted file mode 100644 index d87ca1945b..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricPotentialDcTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricPotentialDc. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricPotentialDcTestsBase - { - protected abstract double KilovoltsDcInOneVoltDc { get; } - protected abstract double MegavoltsDcInOneVoltDc { get; } - protected abstract double MicrovoltsDcInOneVoltDc { get; } - protected abstract double MillivoltsDcInOneVoltDc { get; } - protected abstract double VoltsDcInOneVoltDc { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsDcTolerance { get { return 1e-5; } } - protected virtual double MegavoltsDcTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsDcTolerance { get { return 1e-5; } } - protected virtual double MillivoltsDcTolerance { get { return 1e-5; } } - protected virtual double VoltsDcTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltDcToElectricPotentialDcUnits() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - AssertEx.EqualTolerance(KilovoltsDcInOneVoltDc, voltdc.KilovoltsDc, KilovoltsDcTolerance); - AssertEx.EqualTolerance(MegavoltsDcInOneVoltDc, voltdc.MegavoltsDc, MegavoltsDcTolerance); - AssertEx.EqualTolerance(MicrovoltsDcInOneVoltDc, voltdc.MicrovoltsDc, MicrovoltsDcTolerance); - AssertEx.EqualTolerance(MillivoltsDcInOneVoltDc, voltdc.MillivoltsDc, MillivoltsDcTolerance); - AssertEx.EqualTolerance(VoltsDcInOneVoltDc, voltdc.VoltsDc, VoltsDcTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricPotentialDc.From(1, ElectricPotentialDcUnit.KilovoltDc).KilovoltsDc, KilovoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.From(1, ElectricPotentialDcUnit.MegavoltDc).MegavoltsDc, MegavoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.From(1, ElectricPotentialDcUnit.MicrovoltDc).MicrovoltsDc, MicrovoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.From(1, ElectricPotentialDcUnit.MillivoltDc).MillivoltsDc, MillivoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.From(1, ElectricPotentialDcUnit.VoltDc).VoltsDc, VoltsDcTolerance); - } - - [Fact] - public void As() - { - var voltdc = ElectricPotentialDc.FromVoltsDc(1); - AssertEx.EqualTolerance(KilovoltsDcInOneVoltDc, voltdc.As(ElectricPotentialDcUnit.KilovoltDc), KilovoltsDcTolerance); - AssertEx.EqualTolerance(MegavoltsDcInOneVoltDc, voltdc.As(ElectricPotentialDcUnit.MegavoltDc), MegavoltsDcTolerance); - AssertEx.EqualTolerance(MicrovoltsDcInOneVoltDc, voltdc.As(ElectricPotentialDcUnit.MicrovoltDc), MicrovoltsDcTolerance); - AssertEx.EqualTolerance(MillivoltsDcInOneVoltDc, voltdc.As(ElectricPotentialDcUnit.MillivoltDc), MillivoltsDcTolerance); - AssertEx.EqualTolerance(VoltsDcInOneVoltDc, voltdc.As(ElectricPotentialDcUnit.VoltDc), VoltsDcTolerance); - } - - [Fact] - public void ToUnit() - { - var voltdc = ElectricPotentialDc.FromVoltsDc(1); - - var kilovoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.KilovoltDc); - AssertEx.EqualTolerance(KilovoltsDcInOneVoltDc, (double)kilovoltdcQuantity.Value, KilovoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.KilovoltDc, kilovoltdcQuantity.Unit); - - var megavoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MegavoltDc); - AssertEx.EqualTolerance(MegavoltsDcInOneVoltDc, (double)megavoltdcQuantity.Value, MegavoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MegavoltDc, megavoltdcQuantity.Unit); - - var microvoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MicrovoltDc); - AssertEx.EqualTolerance(MicrovoltsDcInOneVoltDc, (double)microvoltdcQuantity.Value, MicrovoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MicrovoltDc, microvoltdcQuantity.Unit); - - var millivoltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.MillivoltDc); - AssertEx.EqualTolerance(MillivoltsDcInOneVoltDc, (double)millivoltdcQuantity.Value, MillivoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.MillivoltDc, millivoltdcQuantity.Unit); - - var voltdcQuantity = voltdc.ToUnit(ElectricPotentialDcUnit.VoltDc); - AssertEx.EqualTolerance(VoltsDcInOneVoltDc, (double)voltdcQuantity.Value, VoltsDcTolerance); - Assert.Equal(ElectricPotentialDcUnit.VoltDc, voltdcQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - AssertEx.EqualTolerance(1, ElectricPotentialDc.FromKilovoltsDc(voltdc.KilovoltsDc).VoltsDc, KilovoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.FromMegavoltsDc(voltdc.MegavoltsDc).VoltsDc, MegavoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.FromMicrovoltsDc(voltdc.MicrovoltsDc).VoltsDc, MicrovoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.FromMillivoltsDc(voltdc.MillivoltsDc).VoltsDc, MillivoltsDcTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialDc.FromVoltsDc(voltdc.VoltsDc).VoltsDc, VoltsDcTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricPotentialDc v = ElectricPotentialDc.FromVoltsDc(1); - AssertEx.EqualTolerance(-1, -v.VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialDc.FromVoltsDc(3)-v).VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialDc.FromVoltsDc(10)/5).VoltsDc, VoltsDcTolerance); - AssertEx.EqualTolerance(2, ElectricPotentialDc.FromVoltsDc(10)/ElectricPotentialDc.FromVoltsDc(5), VoltsDcTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricPotentialDc oneVoltDc = ElectricPotentialDc.FromVoltsDc(1); - ElectricPotentialDc twoVoltsDc = ElectricPotentialDc.FromVoltsDc(2); - - Assert.True(oneVoltDc < twoVoltsDc); - Assert.True(oneVoltDc <= twoVoltsDc); - Assert.True(twoVoltsDc > oneVoltDc); - Assert.True(twoVoltsDc >= oneVoltDc); - - Assert.False(oneVoltDc > twoVoltsDc); - Assert.False(oneVoltDc >= twoVoltsDc); - Assert.False(twoVoltsDc < oneVoltDc); - Assert.False(twoVoltsDc <= oneVoltDc); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - Assert.Equal(0, voltdc.CompareTo(voltdc)); - Assert.True(voltdc.CompareTo(ElectricPotentialDc.Zero) > 0); - Assert.True(ElectricPotentialDc.Zero.CompareTo(voltdc) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - Assert.Throws(() => voltdc.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - Assert.Throws(() => voltdc.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricPotentialDc a = ElectricPotentialDc.FromVoltsDc(1); - ElectricPotentialDc b = ElectricPotentialDc.FromVoltsDc(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricPotentialDc v = ElectricPotentialDc.FromVoltsDc(1); - Assert.True(v.Equals(ElectricPotentialDc.FromVoltsDc(1), ElectricPotentialDc.FromVoltsDc(VoltsDcTolerance))); - Assert.False(v.Equals(ElectricPotentialDc.Zero, ElectricPotentialDc.FromVoltsDc(VoltsDcTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - Assert.False(voltdc.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricPotentialDc voltdc = ElectricPotentialDc.FromVoltsDc(1); - Assert.False(voltdc.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialDcUnit.Undefined, ElectricPotentialDc.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricPotentialTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricPotentialTestsBase.g.cs deleted file mode 100644 index b3f20c8c98..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricPotentialTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricPotential. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricPotentialTestsBase - { - protected abstract double KilovoltsInOneVolt { get; } - protected abstract double MegavoltsInOneVolt { get; } - protected abstract double MicrovoltsInOneVolt { get; } - protected abstract double MillivoltsInOneVolt { get; } - protected abstract double VoltsInOneVolt { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltsTolerance { get { return 1e-5; } } - protected virtual double MegavoltsTolerance { get { return 1e-5; } } - protected virtual double MicrovoltsTolerance { get { return 1e-5; } } - protected virtual double MillivoltsTolerance { get { return 1e-5; } } - protected virtual double VoltsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltToElectricPotentialUnits() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(KilovoltsInOneVolt, volt.Kilovolts, KilovoltsTolerance); - AssertEx.EqualTolerance(MegavoltsInOneVolt, volt.Megavolts, MegavoltsTolerance); - AssertEx.EqualTolerance(MicrovoltsInOneVolt, volt.Microvolts, MicrovoltsTolerance); - AssertEx.EqualTolerance(MillivoltsInOneVolt, volt.Millivolts, MillivoltsTolerance); - AssertEx.EqualTolerance(VoltsInOneVolt, volt.Volts, VoltsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricPotential.From(1, ElectricPotentialUnit.Kilovolt).Kilovolts, KilovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.From(1, ElectricPotentialUnit.Megavolt).Megavolts, MegavoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.From(1, ElectricPotentialUnit.Microvolt).Microvolts, MicrovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.From(1, ElectricPotentialUnit.Millivolt).Millivolts, MillivoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.From(1, ElectricPotentialUnit.Volt).Volts, VoltsTolerance); - } - - [Fact] - public void As() - { - var volt = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(KilovoltsInOneVolt, volt.As(ElectricPotentialUnit.Kilovolt), KilovoltsTolerance); - AssertEx.EqualTolerance(MegavoltsInOneVolt, volt.As(ElectricPotentialUnit.Megavolt), MegavoltsTolerance); - AssertEx.EqualTolerance(MicrovoltsInOneVolt, volt.As(ElectricPotentialUnit.Microvolt), MicrovoltsTolerance); - AssertEx.EqualTolerance(MillivoltsInOneVolt, volt.As(ElectricPotentialUnit.Millivolt), MillivoltsTolerance); - AssertEx.EqualTolerance(VoltsInOneVolt, volt.As(ElectricPotentialUnit.Volt), VoltsTolerance); - } - - [Fact] - public void ToUnit() - { - var volt = ElectricPotential.FromVolts(1); - - var kilovoltQuantity = volt.ToUnit(ElectricPotentialUnit.Kilovolt); - AssertEx.EqualTolerance(KilovoltsInOneVolt, (double)kilovoltQuantity.Value, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, kilovoltQuantity.Unit); - - var megavoltQuantity = volt.ToUnit(ElectricPotentialUnit.Megavolt); - AssertEx.EqualTolerance(MegavoltsInOneVolt, (double)megavoltQuantity.Value, MegavoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Megavolt, megavoltQuantity.Unit); - - var microvoltQuantity = volt.ToUnit(ElectricPotentialUnit.Microvolt); - AssertEx.EqualTolerance(MicrovoltsInOneVolt, (double)microvoltQuantity.Value, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, microvoltQuantity.Unit); - - var millivoltQuantity = volt.ToUnit(ElectricPotentialUnit.Millivolt); - AssertEx.EqualTolerance(MillivoltsInOneVolt, (double)millivoltQuantity.Value, MillivoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Millivolt, millivoltQuantity.Unit); - - var voltQuantity = volt.ToUnit(ElectricPotentialUnit.Volt); - AssertEx.EqualTolerance(VoltsInOneVolt, (double)voltQuantity.Value, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, voltQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(1, ElectricPotential.FromKilovolts(volt.Kilovolts).Volts, KilovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMegavolts(volt.Megavolts).Volts, MegavoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMicrovolts(volt.Microvolts).Volts, MicrovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMillivolts(volt.Millivolts).Volts, MillivoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromVolts(volt.Volts).Volts, VoltsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricPotential v = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(-1, -v.Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (ElectricPotential.FromVolts(3)-v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (v + v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(10, (v*10).Volts, VoltsTolerance); - AssertEx.EqualTolerance(10, (10*v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (ElectricPotential.FromVolts(10)/5).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, ElectricPotential.FromVolts(10)/ElectricPotential.FromVolts(5), VoltsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricPotential oneVolt = ElectricPotential.FromVolts(1); - ElectricPotential twoVolts = ElectricPotential.FromVolts(2); - - Assert.True(oneVolt < twoVolts); - Assert.True(oneVolt <= twoVolts); - Assert.True(twoVolts > oneVolt); - Assert.True(twoVolts >= oneVolt); - - Assert.False(oneVolt > twoVolts); - Assert.False(oneVolt >= twoVolts); - Assert.False(twoVolts < oneVolt); - Assert.False(twoVolts <= oneVolt); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.Equal(0, volt.CompareTo(volt)); - Assert.True(volt.CompareTo(ElectricPotential.Zero) > 0); - Assert.True(ElectricPotential.Zero.CompareTo(volt) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.Throws(() => volt.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.Throws(() => volt.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricPotential a = ElectricPotential.FromVolts(1); - ElectricPotential b = ElectricPotential.FromVolts(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricPotential v = ElectricPotential.FromVolts(1); - Assert.True(v.Equals(ElectricPotential.FromVolts(1), ElectricPotential.FromVolts(VoltsTolerance))); - Assert.False(v.Equals(ElectricPotential.Zero, ElectricPotential.FromVolts(VoltsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.False(volt.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.False(volt.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialUnit.Undefined, ElectricPotential.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricResistanceTestsBase.g.cs deleted file mode 100644 index 0cec03a766..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricResistanceTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricResistance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricResistanceTestsBase - { - protected abstract double GigaohmsInOneOhm { get; } - protected abstract double KiloohmsInOneOhm { get; } - protected abstract double MegaohmsInOneOhm { get; } - protected abstract double MilliohmsInOneOhm { get; } - protected abstract double OhmsInOneOhm { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigaohmsTolerance { get { return 1e-5; } } - protected virtual double KiloohmsTolerance { get { return 1e-5; } } - protected virtual double MegaohmsTolerance { get { return 1e-5; } } - protected virtual double MilliohmsTolerance { get { return 1e-5; } } - protected virtual double OhmsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void OhmToElectricResistanceUnits() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(GigaohmsInOneOhm, ohm.Gigaohms, GigaohmsTolerance); - AssertEx.EqualTolerance(KiloohmsInOneOhm, ohm.Kiloohms, KiloohmsTolerance); - AssertEx.EqualTolerance(MegaohmsInOneOhm, ohm.Megaohms, MegaohmsTolerance); - AssertEx.EqualTolerance(MilliohmsInOneOhm, ohm.Milliohms, MilliohmsTolerance); - AssertEx.EqualTolerance(OhmsInOneOhm, ohm.Ohms, OhmsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricResistance.From(1, ElectricResistanceUnit.Gigaohm).Gigaohms, GigaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.From(1, ElectricResistanceUnit.Kiloohm).Kiloohms, KiloohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.From(1, ElectricResistanceUnit.Megaohm).Megaohms, MegaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.From(1, ElectricResistanceUnit.Milliohm).Milliohms, MilliohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.From(1, ElectricResistanceUnit.Ohm).Ohms, OhmsTolerance); - } - - [Fact] - public void As() - { - var ohm = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(GigaohmsInOneOhm, ohm.As(ElectricResistanceUnit.Gigaohm), GigaohmsTolerance); - AssertEx.EqualTolerance(KiloohmsInOneOhm, ohm.As(ElectricResistanceUnit.Kiloohm), KiloohmsTolerance); - AssertEx.EqualTolerance(MegaohmsInOneOhm, ohm.As(ElectricResistanceUnit.Megaohm), MegaohmsTolerance); - AssertEx.EqualTolerance(MilliohmsInOneOhm, ohm.As(ElectricResistanceUnit.Milliohm), MilliohmsTolerance); - AssertEx.EqualTolerance(OhmsInOneOhm, ohm.As(ElectricResistanceUnit.Ohm), OhmsTolerance); - } - - [Fact] - public void ToUnit() - { - var ohm = ElectricResistance.FromOhms(1); - - var gigaohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Gigaohm); - AssertEx.EqualTolerance(GigaohmsInOneOhm, (double)gigaohmQuantity.Value, GigaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Gigaohm, gigaohmQuantity.Unit); - - var kiloohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Kiloohm); - AssertEx.EqualTolerance(KiloohmsInOneOhm, (double)kiloohmQuantity.Value, KiloohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Kiloohm, kiloohmQuantity.Unit); - - var megaohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Megaohm); - AssertEx.EqualTolerance(MegaohmsInOneOhm, (double)megaohmQuantity.Value, MegaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Megaohm, megaohmQuantity.Unit); - - var milliohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Milliohm); - AssertEx.EqualTolerance(MilliohmsInOneOhm, (double)milliohmQuantity.Value, MilliohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Milliohm, milliohmQuantity.Unit); - - var ohmQuantity = ohm.ToUnit(ElectricResistanceUnit.Ohm); - AssertEx.EqualTolerance(OhmsInOneOhm, (double)ohmQuantity.Value, OhmsTolerance); - Assert.Equal(ElectricResistanceUnit.Ohm, ohmQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(1, ElectricResistance.FromGigaohms(ohm.Gigaohms).Ohms, GigaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromKiloohms(ohm.Kiloohms).Ohms, KiloohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromMegaohms(ohm.Megaohms).Ohms, MegaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromMilliohms(ohm.Milliohms).Ohms, MilliohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromOhms(ohm.Ohms).Ohms, OhmsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricResistance v = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(-1, -v.Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricResistance.FromOhms(3)-v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (v + v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (v*10).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (10*v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricResistance.FromOhms(10)/5).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, ElectricResistance.FromOhms(10)/ElectricResistance.FromOhms(5), OhmsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricResistance oneOhm = ElectricResistance.FromOhms(1); - ElectricResistance twoOhms = ElectricResistance.FromOhms(2); - - Assert.True(oneOhm < twoOhms); - Assert.True(oneOhm <= twoOhms); - Assert.True(twoOhms > oneOhm); - Assert.True(twoOhms >= oneOhm); - - Assert.False(oneOhm > twoOhms); - Assert.False(oneOhm >= twoOhms); - Assert.False(twoOhms < oneOhm); - Assert.False(twoOhms <= oneOhm); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.Equal(0, ohm.CompareTo(ohm)); - Assert.True(ohm.CompareTo(ElectricResistance.Zero) > 0); - Assert.True(ElectricResistance.Zero.CompareTo(ohm) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.Throws(() => ohm.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.Throws(() => ohm.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricResistance a = ElectricResistance.FromOhms(1); - ElectricResistance b = ElectricResistance.FromOhms(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricResistance v = ElectricResistance.FromOhms(1); - Assert.True(v.Equals(ElectricResistance.FromOhms(1), ElectricResistance.FromOhms(OhmsTolerance))); - Assert.False(v.Equals(ElectricResistance.Zero, ElectricResistance.FromOhms(OhmsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.False(ohm.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.False(ohm.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricResistanceUnit.Undefined, ElectricResistance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ElectricResistivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ElectricResistivityTestsBase.g.cs deleted file mode 100644 index af17382b28..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ElectricResistivityTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ElectricResistivity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ElectricResistivityTestsBase - { - protected abstract double MicroohmMetersInOneOhmMeter { get; } - protected abstract double MilliohmMetersInOneOhmMeter { get; } - protected abstract double NanoohmMetersInOneOhmMeter { get; } - protected abstract double OhmMetersInOneOhmMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicroohmMetersTolerance { get { return 1e-5; } } - protected virtual double MilliohmMetersTolerance { get { return 1e-5; } } - protected virtual double NanoohmMetersTolerance { get { return 1e-5; } } - protected virtual double OhmMetersTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void OhmMeterToElectricResistivityUnits() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(MicroohmMetersInOneOhmMeter, ohmmeter.MicroohmMeters, MicroohmMetersTolerance); - AssertEx.EqualTolerance(MilliohmMetersInOneOhmMeter, ohmmeter.MilliohmMeters, MilliohmMetersTolerance); - AssertEx.EqualTolerance(NanoohmMetersInOneOhmMeter, ohmmeter.NanoohmMeters, NanoohmMetersTolerance); - AssertEx.EqualTolerance(OhmMetersInOneOhmMeter, ohmmeter.OhmMeters, OhmMetersTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ElectricResistivity.From(1, ElectricResistivityUnit.MicroohmMeter).MicroohmMeters, MicroohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.From(1, ElectricResistivityUnit.MilliohmMeter).MilliohmMeters, MilliohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.From(1, ElectricResistivityUnit.NanoohmMeter).NanoohmMeters, NanoohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.From(1, ElectricResistivityUnit.OhmMeter).OhmMeters, OhmMetersTolerance); - } - - [Fact] - public void As() - { - var ohmmeter = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(MicroohmMetersInOneOhmMeter, ohmmeter.As(ElectricResistivityUnit.MicroohmMeter), MicroohmMetersTolerance); - AssertEx.EqualTolerance(MilliohmMetersInOneOhmMeter, ohmmeter.As(ElectricResistivityUnit.MilliohmMeter), MilliohmMetersTolerance); - AssertEx.EqualTolerance(NanoohmMetersInOneOhmMeter, ohmmeter.As(ElectricResistivityUnit.NanoohmMeter), NanoohmMetersTolerance); - AssertEx.EqualTolerance(OhmMetersInOneOhmMeter, ohmmeter.As(ElectricResistivityUnit.OhmMeter), OhmMetersTolerance); - } - - [Fact] - public void ToUnit() - { - var ohmmeter = ElectricResistivity.FromOhmMeters(1); - - var microohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MicroohmMeter); - AssertEx.EqualTolerance(MicroohmMetersInOneOhmMeter, (double)microohmmeterQuantity.Value, MicroohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmMeter, microohmmeterQuantity.Unit); - - var milliohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.MilliohmMeter); - AssertEx.EqualTolerance(MilliohmMetersInOneOhmMeter, (double)milliohmmeterQuantity.Value, MilliohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MilliohmMeter, milliohmmeterQuantity.Unit); - - var nanoohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.NanoohmMeter); - AssertEx.EqualTolerance(NanoohmMetersInOneOhmMeter, (double)nanoohmmeterQuantity.Value, NanoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmMeter, nanoohmmeterQuantity.Unit); - - var ohmmeterQuantity = ohmmeter.ToUnit(ElectricResistivityUnit.OhmMeter); - AssertEx.EqualTolerance(OhmMetersInOneOhmMeter, (double)ohmmeterQuantity.Value, OhmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.OhmMeter, ohmmeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMicroohmMeters(ohmmeter.MicroohmMeters).OhmMeters, MicroohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMilliohmMeters(ohmmeter.MilliohmMeters).OhmMeters, MilliohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromNanoohmMeters(ohmmeter.NanoohmMeters).OhmMeters, NanoohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromOhmMeters(ohmmeter.OhmMeters).OhmMeters, OhmMetersTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ElectricResistivity v = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(-1, -v.OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (ElectricResistivity.FromOhmMeters(3)-v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (ElectricResistivity.FromOhmMeters(10)/5).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, ElectricResistivity.FromOhmMeters(10)/ElectricResistivity.FromOhmMeters(5), OhmMetersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ElectricResistivity oneOhmMeter = ElectricResistivity.FromOhmMeters(1); - ElectricResistivity twoOhmMeters = ElectricResistivity.FromOhmMeters(2); - - Assert.True(oneOhmMeter < twoOhmMeters); - Assert.True(oneOhmMeter <= twoOhmMeters); - Assert.True(twoOhmMeters > oneOhmMeter); - Assert.True(twoOhmMeters >= oneOhmMeter); - - Assert.False(oneOhmMeter > twoOhmMeters); - Assert.False(oneOhmMeter >= twoOhmMeters); - Assert.False(twoOhmMeters < oneOhmMeter); - Assert.False(twoOhmMeters <= oneOhmMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.Equal(0, ohmmeter.CompareTo(ohmmeter)); - Assert.True(ohmmeter.CompareTo(ElectricResistivity.Zero) > 0); - Assert.True(ElectricResistivity.Zero.CompareTo(ohmmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.Throws(() => ohmmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.Throws(() => ohmmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ElectricResistivity a = ElectricResistivity.FromOhmMeters(1); - ElectricResistivity b = ElectricResistivity.FromOhmMeters(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ElectricResistivity v = ElectricResistivity.FromOhmMeters(1); - Assert.True(v.Equals(ElectricResistivity.FromOhmMeters(1), ElectricResistivity.FromOhmMeters(OhmMetersTolerance))); - Assert.False(v.Equals(ElectricResistivity.Zero, ElectricResistivity.FromOhmMeters(OhmMetersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.False(ohmmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.False(ohmmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricResistivityUnit.Undefined, ElectricResistivity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/EnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/EnergyTestsBase.g.cs deleted file mode 100644 index 9b33409387..0000000000 --- a/UnitsNet.Tests/GeneratedCode/EnergyTestsBase.g.cs +++ /dev/null @@ -1,407 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Energy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class EnergyTestsBase - { - protected abstract double BritishThermalUnitsInOneJoule { get; } - protected abstract double CaloriesInOneJoule { get; } - protected abstract double DecathermsEcInOneJoule { get; } - protected abstract double DecathermsImperialInOneJoule { get; } - protected abstract double DecathermsUsInOneJoule { get; } - protected abstract double ElectronVoltsInOneJoule { get; } - protected abstract double ErgsInOneJoule { get; } - protected abstract double FootPoundsInOneJoule { get; } - protected abstract double GigabritishThermalUnitsInOneJoule { get; } - protected abstract double GigawattHoursInOneJoule { get; } - protected abstract double JoulesInOneJoule { get; } - protected abstract double KilobritishThermalUnitsInOneJoule { get; } - protected abstract double KilocaloriesInOneJoule { get; } - protected abstract double KilojoulesInOneJoule { get; } - protected abstract double KilowattHoursInOneJoule { get; } - protected abstract double MegabritishThermalUnitsInOneJoule { get; } - protected abstract double MegajoulesInOneJoule { get; } - protected abstract double MegawattHoursInOneJoule { get; } - protected abstract double ThermsEcInOneJoule { get; } - protected abstract double ThermsImperialInOneJoule { get; } - protected abstract double ThermsUsInOneJoule { get; } - protected abstract double WattHoursInOneJoule { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double CaloriesTolerance { get { return 1e-5; } } - protected virtual double DecathermsEcTolerance { get { return 1e-5; } } - protected virtual double DecathermsImperialTolerance { get { return 1e-5; } } - protected virtual double DecathermsUsTolerance { get { return 1e-5; } } - protected virtual double ElectronVoltsTolerance { get { return 1e-5; } } - protected virtual double ErgsTolerance { get { return 1e-5; } } - protected virtual double FootPoundsTolerance { get { return 1e-5; } } - protected virtual double GigabritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double GigawattHoursTolerance { get { return 1e-5; } } - protected virtual double JoulesTolerance { get { return 1e-5; } } - protected virtual double KilobritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesTolerance { get { return 1e-5; } } - protected virtual double KilojoulesTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursTolerance { get { return 1e-5; } } - protected virtual double MegabritishThermalUnitsTolerance { get { return 1e-5; } } - protected virtual double MegajoulesTolerance { get { return 1e-5; } } - protected virtual double MegawattHoursTolerance { get { return 1e-5; } } - protected virtual double ThermsEcTolerance { get { return 1e-5; } } - protected virtual double ThermsImperialTolerance { get { return 1e-5; } } - protected virtual double ThermsUsTolerance { get { return 1e-5; } } - protected virtual double WattHoursTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JouleToEnergyUnits() - { - Energy joule = Energy.FromJoules(1); - AssertEx.EqualTolerance(BritishThermalUnitsInOneJoule, joule.BritishThermalUnits, BritishThermalUnitsTolerance); - AssertEx.EqualTolerance(CaloriesInOneJoule, joule.Calories, CaloriesTolerance); - AssertEx.EqualTolerance(DecathermsEcInOneJoule, joule.DecathermsEc, DecathermsEcTolerance); - AssertEx.EqualTolerance(DecathermsImperialInOneJoule, joule.DecathermsImperial, DecathermsImperialTolerance); - AssertEx.EqualTolerance(DecathermsUsInOneJoule, joule.DecathermsUs, DecathermsUsTolerance); - AssertEx.EqualTolerance(ElectronVoltsInOneJoule, joule.ElectronVolts, ElectronVoltsTolerance); - AssertEx.EqualTolerance(ErgsInOneJoule, joule.Ergs, ErgsTolerance); - AssertEx.EqualTolerance(FootPoundsInOneJoule, joule.FootPounds, FootPoundsTolerance); - AssertEx.EqualTolerance(GigabritishThermalUnitsInOneJoule, joule.GigabritishThermalUnits, GigabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(GigawattHoursInOneJoule, joule.GigawattHours, GigawattHoursTolerance); - AssertEx.EqualTolerance(JoulesInOneJoule, joule.Joules, JoulesTolerance); - AssertEx.EqualTolerance(KilobritishThermalUnitsInOneJoule, joule.KilobritishThermalUnits, KilobritishThermalUnitsTolerance); - AssertEx.EqualTolerance(KilocaloriesInOneJoule, joule.Kilocalories, KilocaloriesTolerance); - AssertEx.EqualTolerance(KilojoulesInOneJoule, joule.Kilojoules, KilojoulesTolerance); - AssertEx.EqualTolerance(KilowattHoursInOneJoule, joule.KilowattHours, KilowattHoursTolerance); - AssertEx.EqualTolerance(MegabritishThermalUnitsInOneJoule, joule.MegabritishThermalUnits, MegabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(MegajoulesInOneJoule, joule.Megajoules, MegajoulesTolerance); - AssertEx.EqualTolerance(MegawattHoursInOneJoule, joule.MegawattHours, MegawattHoursTolerance); - AssertEx.EqualTolerance(ThermsEcInOneJoule, joule.ThermsEc, ThermsEcTolerance); - AssertEx.EqualTolerance(ThermsImperialInOneJoule, joule.ThermsImperial, ThermsImperialTolerance); - AssertEx.EqualTolerance(ThermsUsInOneJoule, joule.ThermsUs, ThermsUsTolerance); - AssertEx.EqualTolerance(WattHoursInOneJoule, joule.WattHours, WattHoursTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.BritishThermalUnit).BritishThermalUnits, BritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Calorie).Calories, CaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.DecathermEc).DecathermsEc, DecathermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.DecathermImperial).DecathermsImperial, DecathermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.DecathermUs).DecathermsUs, DecathermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.ElectronVolt).ElectronVolts, ElectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Erg).Ergs, ErgsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.FootPound).FootPounds, FootPoundsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.GigabritishThermalUnit).GigabritishThermalUnits, GigabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.GigawattHour).GigawattHours, GigawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Joule).Joules, JoulesTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.KilobritishThermalUnit).KilobritishThermalUnits, KilobritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Kilocalorie).Kilocalories, KilocaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Kilojoule).Kilojoules, KilojoulesTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.KilowattHour).KilowattHours, KilowattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.MegabritishThermalUnit).MegabritishThermalUnits, MegabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.Megajoule).Megajoules, MegajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.MegawattHour).MegawattHours, MegawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.ThermEc).ThermsEc, ThermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.ThermImperial).ThermsImperial, ThermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.ThermUs).ThermsUs, ThermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.From(1, EnergyUnit.WattHour).WattHours, WattHoursTolerance); - } - - [Fact] - public void As() - { - var joule = Energy.FromJoules(1); - AssertEx.EqualTolerance(BritishThermalUnitsInOneJoule, joule.As(EnergyUnit.BritishThermalUnit), BritishThermalUnitsTolerance); - AssertEx.EqualTolerance(CaloriesInOneJoule, joule.As(EnergyUnit.Calorie), CaloriesTolerance); - AssertEx.EqualTolerance(DecathermsEcInOneJoule, joule.As(EnergyUnit.DecathermEc), DecathermsEcTolerance); - AssertEx.EqualTolerance(DecathermsImperialInOneJoule, joule.As(EnergyUnit.DecathermImperial), DecathermsImperialTolerance); - AssertEx.EqualTolerance(DecathermsUsInOneJoule, joule.As(EnergyUnit.DecathermUs), DecathermsUsTolerance); - AssertEx.EqualTolerance(ElectronVoltsInOneJoule, joule.As(EnergyUnit.ElectronVolt), ElectronVoltsTolerance); - AssertEx.EqualTolerance(ErgsInOneJoule, joule.As(EnergyUnit.Erg), ErgsTolerance); - AssertEx.EqualTolerance(FootPoundsInOneJoule, joule.As(EnergyUnit.FootPound), FootPoundsTolerance); - AssertEx.EqualTolerance(GigabritishThermalUnitsInOneJoule, joule.As(EnergyUnit.GigabritishThermalUnit), GigabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(GigawattHoursInOneJoule, joule.As(EnergyUnit.GigawattHour), GigawattHoursTolerance); - AssertEx.EqualTolerance(JoulesInOneJoule, joule.As(EnergyUnit.Joule), JoulesTolerance); - AssertEx.EqualTolerance(KilobritishThermalUnitsInOneJoule, joule.As(EnergyUnit.KilobritishThermalUnit), KilobritishThermalUnitsTolerance); - AssertEx.EqualTolerance(KilocaloriesInOneJoule, joule.As(EnergyUnit.Kilocalorie), KilocaloriesTolerance); - AssertEx.EqualTolerance(KilojoulesInOneJoule, joule.As(EnergyUnit.Kilojoule), KilojoulesTolerance); - AssertEx.EqualTolerance(KilowattHoursInOneJoule, joule.As(EnergyUnit.KilowattHour), KilowattHoursTolerance); - AssertEx.EqualTolerance(MegabritishThermalUnitsInOneJoule, joule.As(EnergyUnit.MegabritishThermalUnit), MegabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(MegajoulesInOneJoule, joule.As(EnergyUnit.Megajoule), MegajoulesTolerance); - AssertEx.EqualTolerance(MegawattHoursInOneJoule, joule.As(EnergyUnit.MegawattHour), MegawattHoursTolerance); - AssertEx.EqualTolerance(ThermsEcInOneJoule, joule.As(EnergyUnit.ThermEc), ThermsEcTolerance); - AssertEx.EqualTolerance(ThermsImperialInOneJoule, joule.As(EnergyUnit.ThermImperial), ThermsImperialTolerance); - AssertEx.EqualTolerance(ThermsUsInOneJoule, joule.As(EnergyUnit.ThermUs), ThermsUsTolerance); - AssertEx.EqualTolerance(WattHoursInOneJoule, joule.As(EnergyUnit.WattHour), WattHoursTolerance); - } - - [Fact] - public void ToUnit() - { - var joule = Energy.FromJoules(1); - - var britishthermalunitQuantity = joule.ToUnit(EnergyUnit.BritishThermalUnit); - AssertEx.EqualTolerance(BritishThermalUnitsInOneJoule, (double)britishthermalunitQuantity.Value, BritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.BritishThermalUnit, britishthermalunitQuantity.Unit); - - var calorieQuantity = joule.ToUnit(EnergyUnit.Calorie); - AssertEx.EqualTolerance(CaloriesInOneJoule, (double)calorieQuantity.Value, CaloriesTolerance); - Assert.Equal(EnergyUnit.Calorie, calorieQuantity.Unit); - - var decathermecQuantity = joule.ToUnit(EnergyUnit.DecathermEc); - AssertEx.EqualTolerance(DecathermsEcInOneJoule, (double)decathermecQuantity.Value, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, decathermecQuantity.Unit); - - var decathermimperialQuantity = joule.ToUnit(EnergyUnit.DecathermImperial); - AssertEx.EqualTolerance(DecathermsImperialInOneJoule, (double)decathermimperialQuantity.Value, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, decathermimperialQuantity.Unit); - - var decathermusQuantity = joule.ToUnit(EnergyUnit.DecathermUs); - AssertEx.EqualTolerance(DecathermsUsInOneJoule, (double)decathermusQuantity.Value, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, decathermusQuantity.Unit); - - var electronvoltQuantity = joule.ToUnit(EnergyUnit.ElectronVolt); - AssertEx.EqualTolerance(ElectronVoltsInOneJoule, (double)electronvoltQuantity.Value, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, electronvoltQuantity.Unit); - - var ergQuantity = joule.ToUnit(EnergyUnit.Erg); - AssertEx.EqualTolerance(ErgsInOneJoule, (double)ergQuantity.Value, ErgsTolerance); - Assert.Equal(EnergyUnit.Erg, ergQuantity.Unit); - - var footpoundQuantity = joule.ToUnit(EnergyUnit.FootPound); - AssertEx.EqualTolerance(FootPoundsInOneJoule, (double)footpoundQuantity.Value, FootPoundsTolerance); - Assert.Equal(EnergyUnit.FootPound, footpoundQuantity.Unit); - - var gigabritishthermalunitQuantity = joule.ToUnit(EnergyUnit.GigabritishThermalUnit); - AssertEx.EqualTolerance(GigabritishThermalUnitsInOneJoule, (double)gigabritishthermalunitQuantity.Value, GigabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.GigabritishThermalUnit, gigabritishthermalunitQuantity.Unit); - - var gigawatthourQuantity = joule.ToUnit(EnergyUnit.GigawattHour); - AssertEx.EqualTolerance(GigawattHoursInOneJoule, (double)gigawatthourQuantity.Value, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, gigawatthourQuantity.Unit); - - var jouleQuantity = joule.ToUnit(EnergyUnit.Joule); - AssertEx.EqualTolerance(JoulesInOneJoule, (double)jouleQuantity.Value, JoulesTolerance); - Assert.Equal(EnergyUnit.Joule, jouleQuantity.Unit); - - var kilobritishthermalunitQuantity = joule.ToUnit(EnergyUnit.KilobritishThermalUnit); - AssertEx.EqualTolerance(KilobritishThermalUnitsInOneJoule, (double)kilobritishthermalunitQuantity.Value, KilobritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.KilobritishThermalUnit, kilobritishthermalunitQuantity.Unit); - - var kilocalorieQuantity = joule.ToUnit(EnergyUnit.Kilocalorie); - AssertEx.EqualTolerance(KilocaloriesInOneJoule, (double)kilocalorieQuantity.Value, KilocaloriesTolerance); - Assert.Equal(EnergyUnit.Kilocalorie, kilocalorieQuantity.Unit); - - var kilojouleQuantity = joule.ToUnit(EnergyUnit.Kilojoule); - AssertEx.EqualTolerance(KilojoulesInOneJoule, (double)kilojouleQuantity.Value, KilojoulesTolerance); - Assert.Equal(EnergyUnit.Kilojoule, kilojouleQuantity.Unit); - - var kilowatthourQuantity = joule.ToUnit(EnergyUnit.KilowattHour); - AssertEx.EqualTolerance(KilowattHoursInOneJoule, (double)kilowatthourQuantity.Value, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, kilowatthourQuantity.Unit); - - var megabritishthermalunitQuantity = joule.ToUnit(EnergyUnit.MegabritishThermalUnit); - AssertEx.EqualTolerance(MegabritishThermalUnitsInOneJoule, (double)megabritishthermalunitQuantity.Value, MegabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.MegabritishThermalUnit, megabritishthermalunitQuantity.Unit); - - var megajouleQuantity = joule.ToUnit(EnergyUnit.Megajoule); - AssertEx.EqualTolerance(MegajoulesInOneJoule, (double)megajouleQuantity.Value, MegajoulesTolerance); - Assert.Equal(EnergyUnit.Megajoule, megajouleQuantity.Unit); - - var megawatthourQuantity = joule.ToUnit(EnergyUnit.MegawattHour); - AssertEx.EqualTolerance(MegawattHoursInOneJoule, (double)megawatthourQuantity.Value, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, megawatthourQuantity.Unit); - - var thermecQuantity = joule.ToUnit(EnergyUnit.ThermEc); - AssertEx.EqualTolerance(ThermsEcInOneJoule, (double)thermecQuantity.Value, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, thermecQuantity.Unit); - - var thermimperialQuantity = joule.ToUnit(EnergyUnit.ThermImperial); - AssertEx.EqualTolerance(ThermsImperialInOneJoule, (double)thermimperialQuantity.Value, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, thermimperialQuantity.Unit); - - var thermusQuantity = joule.ToUnit(EnergyUnit.ThermUs); - AssertEx.EqualTolerance(ThermsUsInOneJoule, (double)thermusQuantity.Value, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, thermusQuantity.Unit); - - var watthourQuantity = joule.ToUnit(EnergyUnit.WattHour); - AssertEx.EqualTolerance(WattHoursInOneJoule, (double)watthourQuantity.Value, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, watthourQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Energy joule = Energy.FromJoules(1); - AssertEx.EqualTolerance(1, Energy.FromBritishThermalUnits(joule.BritishThermalUnits).Joules, BritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromCalories(joule.Calories).Joules, CaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsEc(joule.DecathermsEc).Joules, DecathermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsImperial(joule.DecathermsImperial).Joules, DecathermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsUs(joule.DecathermsUs).Joules, DecathermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.FromElectronVolts(joule.ElectronVolts).Joules, ElectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromErgs(joule.Ergs).Joules, ErgsTolerance); - AssertEx.EqualTolerance(1, Energy.FromFootPounds(joule.FootPounds).Joules, FootPoundsTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigabritishThermalUnits(joule.GigabritishThermalUnits).Joules, GigabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigawattHours(joule.GigawattHours).Joules, GigawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromJoules(joule.Joules).Joules, JoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilobritishThermalUnits(joule.KilobritishThermalUnits).Joules, KilobritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilocalories(joule.Kilocalories).Joules, KilocaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilojoules(joule.Kilojoules).Joules, KilojoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilowattHours(joule.KilowattHours).Joules, KilowattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegabritishThermalUnits(joule.MegabritishThermalUnits).Joules, MegabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegajoules(joule.Megajoules).Joules, MegajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegawattHours(joule.MegawattHours).Joules, MegawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsEc(joule.ThermsEc).Joules, ThermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsImperial(joule.ThermsImperial).Joules, ThermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsUs(joule.ThermsUs).Joules, ThermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.FromWattHours(joule.WattHours).Joules, WattHoursTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Energy v = Energy.FromJoules(1); - AssertEx.EqualTolerance(-1, -v.Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (Energy.FromJoules(3)-v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (v + v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(10, (v*10).Joules, JoulesTolerance); - AssertEx.EqualTolerance(10, (10*v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (Energy.FromJoules(10)/5).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, Energy.FromJoules(10)/Energy.FromJoules(5), JoulesTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Energy oneJoule = Energy.FromJoules(1); - Energy twoJoules = Energy.FromJoules(2); - - Assert.True(oneJoule < twoJoules); - Assert.True(oneJoule <= twoJoules); - Assert.True(twoJoules > oneJoule); - Assert.True(twoJoules >= oneJoule); - - Assert.False(oneJoule > twoJoules); - Assert.False(oneJoule >= twoJoules); - Assert.False(twoJoules < oneJoule); - Assert.False(twoJoules <= oneJoule); - } - - [Fact] - public void CompareToIsImplemented() - { - Energy joule = Energy.FromJoules(1); - Assert.Equal(0, joule.CompareTo(joule)); - Assert.True(joule.CompareTo(Energy.Zero) > 0); - Assert.True(Energy.Zero.CompareTo(joule) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Energy joule = Energy.FromJoules(1); - Assert.Throws(() => joule.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Energy joule = Energy.FromJoules(1); - Assert.Throws(() => joule.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Energy a = Energy.FromJoules(1); - Energy b = Energy.FromJoules(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Energy v = Energy.FromJoules(1); - Assert.True(v.Equals(Energy.FromJoules(1), Energy.FromJoules(JoulesTolerance))); - Assert.False(v.Equals(Energy.Zero, Energy.FromJoules(JoulesTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Energy joule = Energy.FromJoules(1); - Assert.False(joule.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Energy joule = Energy.FromJoules(1); - Assert.False(joule.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(EnergyUnit.Undefined, Energy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/EntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/EntropyTestsBase.g.cs deleted file mode 100644 index 0e56dca59c..0000000000 --- a/UnitsNet.Tests/GeneratedCode/EntropyTestsBase.g.cs +++ /dev/null @@ -1,257 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Entropy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class EntropyTestsBase - { - protected abstract double CaloriesPerKelvinInOneJoulePerKelvin { get; } - protected abstract double JoulesPerDegreeCelsiusInOneJoulePerKelvin { get; } - protected abstract double JoulesPerKelvinInOneJoulePerKelvin { get; } - protected abstract double KilocaloriesPerKelvinInOneJoulePerKelvin { get; } - protected abstract double KilojoulesPerDegreeCelsiusInOneJoulePerKelvin { get; } - protected abstract double KilojoulesPerKelvinInOneJoulePerKelvin { get; } - protected abstract double MegajoulesPerKelvinInOneJoulePerKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CaloriesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double JoulesPerDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerKelvinToEntropyUnits() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(CaloriesPerKelvinInOneJoulePerKelvin, jouleperkelvin.CaloriesPerKelvin, CaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(JoulesPerDegreeCelsiusInOneJoulePerKelvin, jouleperkelvin.JoulesPerDegreeCelsius, JoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(JoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(KilocaloriesPerKelvinInOneJoulePerKelvin, jouleperkelvin.KilocaloriesPerKelvin, KilocaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerDegreeCelsiusInOneJoulePerKelvin, jouleperkelvin.KilojoulesPerDegreeCelsius, KilojoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(KilojoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.KilojoulesPerKelvin, KilojoulesPerKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.MegajoulesPerKelvin, MegajoulesPerKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.CaloriePerKelvin).CaloriesPerKelvin, CaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.JoulePerDegreeCelsius).JoulesPerDegreeCelsius, JoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.JoulePerKelvin).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.KilocaloriePerKelvin).KilocaloriesPerKelvin, KilocaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.KilojoulePerDegreeCelsius).KilojoulesPerDegreeCelsius, KilojoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.KilojoulePerKelvin).KilojoulesPerKelvin, KilojoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.From(1, EntropyUnit.MegajoulePerKelvin).MegajoulesPerKelvin, MegajoulesPerKelvinTolerance); - } - - [Fact] - public void As() - { - var jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(CaloriesPerKelvinInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.CaloriePerKelvin), CaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(JoulesPerDegreeCelsiusInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.JoulePerDegreeCelsius), JoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(JoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.JoulePerKelvin), JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(KilocaloriesPerKelvinInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.KilocaloriePerKelvin), KilocaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerDegreeCelsiusInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.KilojoulePerDegreeCelsius), KilojoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(KilojoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.KilojoulePerKelvin), KilojoulesPerKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerKelvinInOneJoulePerKelvin, jouleperkelvin.As(EntropyUnit.MegajoulePerKelvin), MegajoulesPerKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - - var calorieperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.CaloriePerKelvin); - AssertEx.EqualTolerance(CaloriesPerKelvinInOneJoulePerKelvin, (double)calorieperkelvinQuantity.Value, CaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.CaloriePerKelvin, calorieperkelvinQuantity.Unit); - - var jouleperdegreecelsiusQuantity = jouleperkelvin.ToUnit(EntropyUnit.JoulePerDegreeCelsius); - AssertEx.EqualTolerance(JoulesPerDegreeCelsiusInOneJoulePerKelvin, (double)jouleperdegreecelsiusQuantity.Value, JoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.JoulePerDegreeCelsius, jouleperdegreecelsiusQuantity.Unit); - - var jouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.JoulePerKelvin); - AssertEx.EqualTolerance(JoulesPerKelvinInOneJoulePerKelvin, (double)jouleperkelvinQuantity.Value, JoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.JoulePerKelvin, jouleperkelvinQuantity.Unit); - - var kilocalorieperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilocaloriePerKelvin); - AssertEx.EqualTolerance(KilocaloriesPerKelvinInOneJoulePerKelvin, (double)kilocalorieperkelvinQuantity.Value, KilocaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilocaloriePerKelvin, kilocalorieperkelvinQuantity.Unit); - - var kilojouleperdegreecelsiusQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilojoulePerDegreeCelsius); - AssertEx.EqualTolerance(KilojoulesPerDegreeCelsiusInOneJoulePerKelvin, (double)kilojouleperdegreecelsiusQuantity.Value, KilojoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.KilojoulePerDegreeCelsius, kilojouleperdegreecelsiusQuantity.Unit); - - var kilojouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.KilojoulePerKelvin); - AssertEx.EqualTolerance(KilojoulesPerKelvinInOneJoulePerKelvin, (double)kilojouleperkelvinQuantity.Value, KilojoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilojoulePerKelvin, kilojouleperkelvinQuantity.Unit); - - var megajouleperkelvinQuantity = jouleperkelvin.ToUnit(EntropyUnit.MegajoulePerKelvin); - AssertEx.EqualTolerance(MegajoulesPerKelvinInOneJoulePerKelvin, (double)megajouleperkelvinQuantity.Value, MegajoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.MegajoulePerKelvin, megajouleperkelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(1, Entropy.FromCaloriesPerKelvin(jouleperkelvin.CaloriesPerKelvin).JoulesPerKelvin, CaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromJoulesPerDegreeCelsius(jouleperkelvin.JoulesPerDegreeCelsius).JoulesPerKelvin, JoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.FromJoulesPerKelvin(jouleperkelvin.JoulesPerKelvin).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilocaloriesPerKelvin(jouleperkelvin.KilocaloriesPerKelvin).JoulesPerKelvin, KilocaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilojoulesPerDegreeCelsius(jouleperkelvin.KilojoulesPerDegreeCelsius).JoulesPerKelvin, KilojoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilojoulesPerKelvin(jouleperkelvin.KilojoulesPerKelvin).JoulesPerKelvin, KilojoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromMegajoulesPerKelvin(jouleperkelvin.MegajoulesPerKelvin).JoulesPerKelvin, MegajoulesPerKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Entropy v = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (Entropy.FromJoulesPerKelvin(3)-v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (Entropy.FromJoulesPerKelvin(10)/5).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, Entropy.FromJoulesPerKelvin(10)/Entropy.FromJoulesPerKelvin(5), JoulesPerKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Entropy oneJoulePerKelvin = Entropy.FromJoulesPerKelvin(1); - Entropy twoJoulesPerKelvin = Entropy.FromJoulesPerKelvin(2); - - Assert.True(oneJoulePerKelvin < twoJoulesPerKelvin); - Assert.True(oneJoulePerKelvin <= twoJoulesPerKelvin); - Assert.True(twoJoulesPerKelvin > oneJoulePerKelvin); - Assert.True(twoJoulesPerKelvin >= oneJoulePerKelvin); - - Assert.False(oneJoulePerKelvin > twoJoulesPerKelvin); - Assert.False(oneJoulePerKelvin >= twoJoulesPerKelvin); - Assert.False(twoJoulesPerKelvin < oneJoulePerKelvin); - Assert.False(twoJoulesPerKelvin <= oneJoulePerKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.Equal(0, jouleperkelvin.CompareTo(jouleperkelvin)); - Assert.True(jouleperkelvin.CompareTo(Entropy.Zero) > 0); - Assert.True(Entropy.Zero.CompareTo(jouleperkelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.Throws(() => jouleperkelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.Throws(() => jouleperkelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Entropy a = Entropy.FromJoulesPerKelvin(1); - Entropy b = Entropy.FromJoulesPerKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Entropy v = Entropy.FromJoulesPerKelvin(1); - Assert.True(v.Equals(Entropy.FromJoulesPerKelvin(1), Entropy.FromJoulesPerKelvin(JoulesPerKelvinTolerance))); - Assert.False(v.Equals(Entropy.Zero, Entropy.FromJoulesPerKelvin(JoulesPerKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.False(jouleperkelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.False(jouleperkelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(EntropyUnit.Undefined, Entropy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/FlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/FlowTestsBase.g.cs deleted file mode 100644 index 3b2b44ce5e..0000000000 --- a/UnitsNet.Tests/GeneratedCode/FlowTestsBase.g.cs +++ /dev/null @@ -1,427 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Flow. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class FlowTestsBase - { - protected abstract double CentilitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double CubicDecimetersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double CubicFeetPerHourInOneCubicMeterPerSecond { get; } - protected abstract double CubicFeetPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double CubicFeetPerSecondInOneCubicMeterPerSecond { get; } - protected abstract double CubicMetersPerHourInOneCubicMeterPerSecond { get; } - protected abstract double CubicMetersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double CubicMetersPerSecondInOneCubicMeterPerSecond { get; } - protected abstract double CubicYardsPerHourInOneCubicMeterPerSecond { get; } - protected abstract double CubicYardsPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double CubicYardsPerSecondInOneCubicMeterPerSecond { get; } - protected abstract double DecilitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double KilolitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double LitersPerHourInOneCubicMeterPerSecond { get; } - protected abstract double LitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double LitersPerSecondInOneCubicMeterPerSecond { get; } - protected abstract double MicrolitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double MillilitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double MillionUsGallonsPerDayInOneCubicMeterPerSecond { get; } - protected abstract double NanolitersPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double OilBarrelsPerDayInOneCubicMeterPerSecond { get; } - protected abstract double UsGallonsPerHourInOneCubicMeterPerSecond { get; } - protected abstract double UsGallonsPerMinuteInOneCubicMeterPerSecond { get; } - protected abstract double UsGallonsPerSecondInOneCubicMeterPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicDecimetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerHourTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double CubicYardsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double LitersPerHourTolerance { get { return 1e-5; } } - protected virtual double LitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double LitersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MillilitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double MillionUsGallonsPerDayTolerance { get { return 1e-5; } } - protected virtual double NanolitersPerMinuteTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsPerDayTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerHourTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double UsGallonsPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CubicMeterPerSecondToFlowUnits() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.CentilitersPerMinute, CentilitersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicFeetPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.CubicFeetPerHour, CubicFeetPerHourTolerance); - AssertEx.EqualTolerance(CubicFeetPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(CubicFeetPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.CubicFeetPerSecond, CubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(CubicMetersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.CubicMetersPerHour, CubicMetersPerHourTolerance); - AssertEx.EqualTolerance(CubicMetersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicMetersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(CubicYardsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.CubicYardsPerHour, CubicYardsPerHourTolerance); - AssertEx.EqualTolerance(CubicYardsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.CubicYardsPerMinute, CubicYardsPerMinuteTolerance); - AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.CubicYardsPerSecond, CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.DecilitersPerMinute, DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.KilolitersPerMinute, KilolitersPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.LitersPerHour, LitersPerHourTolerance); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.LitersPerMinute, LitersPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.LitersPerSecond, LitersPerSecondTolerance); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.MillilitersPerMinute, MillilitersPerMinuteTolerance); - AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.NanolitersPerMinute, NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.OilBarrelsPerDay, OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.UsGallonsPerHour, UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.UsGallonsPerSecond, UsGallonsPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CentilitersPerMinute).CentilitersPerMinute, CentilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicDecimeterPerMinute).CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicFootPerHour).CubicFeetPerHour, CubicFeetPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicFootPerMinute).CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicFootPerSecond).CubicFeetPerSecond, CubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicMeterPerHour).CubicMetersPerHour, CubicMetersPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicMeterPerMinute).CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicMeterPerSecond).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicYardPerHour).CubicYardsPerHour, CubicYardsPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicYardPerMinute).CubicYardsPerMinute, CubicYardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.CubicYardPerSecond).CubicYardsPerSecond, CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.DecilitersPerMinute).DecilitersPerMinute, DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.KilolitersPerMinute).KilolitersPerMinute, KilolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.LitersPerHour).LitersPerHour, LitersPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.LitersPerMinute).LitersPerMinute, LitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.LitersPerSecond).LitersPerSecond, LitersPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.MicrolitersPerMinute).MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.MillilitersPerMinute).MillilitersPerMinute, MillilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.MillionUsGallonsPerDay).MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.NanolitersPerMinute).NanolitersPerMinute, NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.OilBarrelsPerDay).OilBarrelsPerDay, OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.UsGallonsPerHour).UsGallonsPerHour, UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.UsGallonsPerMinute).UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.From(1, FlowUnit.UsGallonsPerSecond).UsGallonsPerSecond, UsGallonsPerSecondTolerance); - } - - [Fact] - public void As() - { - var cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CentilitersPerMinute), CentilitersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicDecimeterPerMinute), CubicDecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicFeetPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicFootPerHour), CubicFeetPerHourTolerance); - AssertEx.EqualTolerance(CubicFeetPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicFootPerMinute), CubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(CubicFeetPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicFootPerSecond), CubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(CubicMetersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicMeterPerHour), CubicMetersPerHourTolerance); - AssertEx.EqualTolerance(CubicMetersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicMeterPerMinute), CubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(CubicMetersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicMeterPerSecond), CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(CubicYardsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicYardPerHour), CubicYardsPerHourTolerance); - AssertEx.EqualTolerance(CubicYardsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicYardPerMinute), CubicYardsPerMinuteTolerance); - AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.CubicYardPerSecond), CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.DecilitersPerMinute), DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.KilolitersPerMinute), KilolitersPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.LitersPerHour), LitersPerHourTolerance); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.LitersPerMinute), LitersPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.LitersPerSecond), LitersPerSecondTolerance); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.MicrolitersPerMinute), MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.MillilitersPerMinute), MillilitersPerMinuteTolerance); - AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.MillionUsGallonsPerDay), MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.NanolitersPerMinute), NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.OilBarrelsPerDay), OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.UsGallonsPerHour), UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.UsGallonsPerMinute), UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(FlowUnit.UsGallonsPerSecond), UsGallonsPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - - var centilitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CentilitersPerMinute); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, (double)centilitersperminuteQuantity.Value, CentilitersPerMinuteTolerance); - Assert.Equal(FlowUnit.CentilitersPerMinute, centilitersperminuteQuantity.Unit); - - var cubicdecimeterperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicDecimeterPerMinute); - AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, (double)cubicdecimeterperminuteQuantity.Value, CubicDecimetersPerMinuteTolerance); - Assert.Equal(FlowUnit.CubicDecimeterPerMinute, cubicdecimeterperminuteQuantity.Unit); - - var cubicfootperhourQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicFootPerHour); - AssertEx.EqualTolerance(CubicFeetPerHourInOneCubicMeterPerSecond, (double)cubicfootperhourQuantity.Value, CubicFeetPerHourTolerance); - Assert.Equal(FlowUnit.CubicFootPerHour, cubicfootperhourQuantity.Unit); - - var cubicfootperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicFootPerMinute); - AssertEx.EqualTolerance(CubicFeetPerMinuteInOneCubicMeterPerSecond, (double)cubicfootperminuteQuantity.Value, CubicFeetPerMinuteTolerance); - Assert.Equal(FlowUnit.CubicFootPerMinute, cubicfootperminuteQuantity.Unit); - - var cubicfootpersecondQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicFootPerSecond); - AssertEx.EqualTolerance(CubicFeetPerSecondInOneCubicMeterPerSecond, (double)cubicfootpersecondQuantity.Value, CubicFeetPerSecondTolerance); - Assert.Equal(FlowUnit.CubicFootPerSecond, cubicfootpersecondQuantity.Unit); - - var cubicmeterperhourQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicMeterPerHour); - AssertEx.EqualTolerance(CubicMetersPerHourInOneCubicMeterPerSecond, (double)cubicmeterperhourQuantity.Value, CubicMetersPerHourTolerance); - Assert.Equal(FlowUnit.CubicMeterPerHour, cubicmeterperhourQuantity.Unit); - - var cubicmeterperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicMeterPerMinute); - AssertEx.EqualTolerance(CubicMetersPerMinuteInOneCubicMeterPerSecond, (double)cubicmeterperminuteQuantity.Value, CubicMetersPerMinuteTolerance); - Assert.Equal(FlowUnit.CubicMeterPerMinute, cubicmeterperminuteQuantity.Unit); - - var cubicmeterpersecondQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicMeterPerSecond); - AssertEx.EqualTolerance(CubicMetersPerSecondInOneCubicMeterPerSecond, (double)cubicmeterpersecondQuantity.Value, CubicMetersPerSecondTolerance); - Assert.Equal(FlowUnit.CubicMeterPerSecond, cubicmeterpersecondQuantity.Unit); - - var cubicyardperhourQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicYardPerHour); - AssertEx.EqualTolerance(CubicYardsPerHourInOneCubicMeterPerSecond, (double)cubicyardperhourQuantity.Value, CubicYardsPerHourTolerance); - Assert.Equal(FlowUnit.CubicYardPerHour, cubicyardperhourQuantity.Unit); - - var cubicyardperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicYardPerMinute); - AssertEx.EqualTolerance(CubicYardsPerMinuteInOneCubicMeterPerSecond, (double)cubicyardperminuteQuantity.Value, CubicYardsPerMinuteTolerance); - Assert.Equal(FlowUnit.CubicYardPerMinute, cubicyardperminuteQuantity.Unit); - - var cubicyardpersecondQuantity = cubicmeterpersecond.ToUnit(FlowUnit.CubicYardPerSecond); - AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, (double)cubicyardpersecondQuantity.Value, CubicYardsPerSecondTolerance); - Assert.Equal(FlowUnit.CubicYardPerSecond, cubicyardpersecondQuantity.Unit); - - var decilitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.DecilitersPerMinute); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, (double)decilitersperminuteQuantity.Value, DecilitersPerMinuteTolerance); - Assert.Equal(FlowUnit.DecilitersPerMinute, decilitersperminuteQuantity.Unit); - - var kilolitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.KilolitersPerMinute); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, (double)kilolitersperminuteQuantity.Value, KilolitersPerMinuteTolerance); - Assert.Equal(FlowUnit.KilolitersPerMinute, kilolitersperminuteQuantity.Unit); - - var litersperhourQuantity = cubicmeterpersecond.ToUnit(FlowUnit.LitersPerHour); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, (double)litersperhourQuantity.Value, LitersPerHourTolerance); - Assert.Equal(FlowUnit.LitersPerHour, litersperhourQuantity.Unit); - - var litersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.LitersPerMinute); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, (double)litersperminuteQuantity.Value, LitersPerMinuteTolerance); - Assert.Equal(FlowUnit.LitersPerMinute, litersperminuteQuantity.Unit); - - var literspersecondQuantity = cubicmeterpersecond.ToUnit(FlowUnit.LitersPerSecond); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, (double)literspersecondQuantity.Value, LitersPerSecondTolerance); - Assert.Equal(FlowUnit.LitersPerSecond, literspersecondQuantity.Unit); - - var microlitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.MicrolitersPerMinute); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, (double)microlitersperminuteQuantity.Value, MicrolitersPerMinuteTolerance); - Assert.Equal(FlowUnit.MicrolitersPerMinute, microlitersperminuteQuantity.Unit); - - var millilitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.MillilitersPerMinute); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, (double)millilitersperminuteQuantity.Value, MillilitersPerMinuteTolerance); - Assert.Equal(FlowUnit.MillilitersPerMinute, millilitersperminuteQuantity.Unit); - - var millionusgallonsperdayQuantity = cubicmeterpersecond.ToUnit(FlowUnit.MillionUsGallonsPerDay); - AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, (double)millionusgallonsperdayQuantity.Value, MillionUsGallonsPerDayTolerance); - Assert.Equal(FlowUnit.MillionUsGallonsPerDay, millionusgallonsperdayQuantity.Unit); - - var nanolitersperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.NanolitersPerMinute); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, (double)nanolitersperminuteQuantity.Value, NanolitersPerMinuteTolerance); - Assert.Equal(FlowUnit.NanolitersPerMinute, nanolitersperminuteQuantity.Unit); - - var oilbarrelsperdayQuantity = cubicmeterpersecond.ToUnit(FlowUnit.OilBarrelsPerDay); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, (double)oilbarrelsperdayQuantity.Value, OilBarrelsPerDayTolerance); - Assert.Equal(FlowUnit.OilBarrelsPerDay, oilbarrelsperdayQuantity.Unit); - - var usgallonsperhourQuantity = cubicmeterpersecond.ToUnit(FlowUnit.UsGallonsPerHour); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, (double)usgallonsperhourQuantity.Value, UsGallonsPerHourTolerance); - Assert.Equal(FlowUnit.UsGallonsPerHour, usgallonsperhourQuantity.Unit); - - var usgallonsperminuteQuantity = cubicmeterpersecond.ToUnit(FlowUnit.UsGallonsPerMinute); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, (double)usgallonsperminuteQuantity.Value, UsGallonsPerMinuteTolerance); - Assert.Equal(FlowUnit.UsGallonsPerMinute, usgallonsperminuteQuantity.Unit); - - var usgallonspersecondQuantity = cubicmeterpersecond.ToUnit(FlowUnit.UsGallonsPerSecond); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, (double)usgallonspersecondQuantity.Value, UsGallonsPerSecondTolerance); - Assert.Equal(FlowUnit.UsGallonsPerSecond, usgallonspersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(1, Flow.FromCentilitersPerMinute(cubicmeterpersecond.CentilitersPerMinute).CubicMetersPerSecond, CentilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicDecimetersPerMinute(cubicmeterpersecond.CubicDecimetersPerMinute).CubicMetersPerSecond, CubicDecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicFeetPerHour(cubicmeterpersecond.CubicFeetPerHour).CubicMetersPerSecond, CubicFeetPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicFeetPerMinute(cubicmeterpersecond.CubicFeetPerMinute).CubicMetersPerSecond, CubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicFeetPerSecond(cubicmeterpersecond.CubicFeetPerSecond).CubicMetersPerSecond, CubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicMetersPerHour(cubicmeterpersecond.CubicMetersPerHour).CubicMetersPerSecond, CubicMetersPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicMetersPerMinute(cubicmeterpersecond.CubicMetersPerMinute).CubicMetersPerSecond, CubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicMetersPerSecond(cubicmeterpersecond.CubicMetersPerSecond).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicYardsPerHour(cubicmeterpersecond.CubicYardsPerHour).CubicMetersPerSecond, CubicYardsPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicYardsPerMinute(cubicmeterpersecond.CubicYardsPerMinute).CubicMetersPerSecond, CubicYardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromCubicYardsPerSecond(cubicmeterpersecond.CubicYardsPerSecond).CubicMetersPerSecond, CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.FromDecilitersPerMinute(cubicmeterpersecond.DecilitersPerMinute).CubicMetersPerSecond, DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromKilolitersPerMinute(cubicmeterpersecond.KilolitersPerMinute).CubicMetersPerSecond, KilolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromLitersPerHour(cubicmeterpersecond.LitersPerHour).CubicMetersPerSecond, LitersPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.FromLitersPerMinute(cubicmeterpersecond.LitersPerMinute).CubicMetersPerSecond, LitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromLitersPerSecond(cubicmeterpersecond.LitersPerSecond).CubicMetersPerSecond, LitersPerSecondTolerance); - AssertEx.EqualTolerance(1, Flow.FromMicrolitersPerMinute(cubicmeterpersecond.MicrolitersPerMinute).CubicMetersPerSecond, MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromMillilitersPerMinute(cubicmeterpersecond.MillilitersPerMinute).CubicMetersPerSecond, MillilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromMillionUsGallonsPerDay(cubicmeterpersecond.MillionUsGallonsPerDay).CubicMetersPerSecond, MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, Flow.FromNanolitersPerMinute(cubicmeterpersecond.NanolitersPerMinute).CubicMetersPerSecond, NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromOilBarrelsPerDay(cubicmeterpersecond.OilBarrelsPerDay).CubicMetersPerSecond, OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(1, Flow.FromUsGallonsPerHour(cubicmeterpersecond.UsGallonsPerHour).CubicMetersPerSecond, UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(1, Flow.FromUsGallonsPerMinute(cubicmeterpersecond.UsGallonsPerMinute).CubicMetersPerSecond, UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Flow.FromUsGallonsPerSecond(cubicmeterpersecond.UsGallonsPerSecond).CubicMetersPerSecond, UsGallonsPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Flow v = Flow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Flow.FromCubicMetersPerSecond(3)-v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Flow.FromCubicMetersPerSecond(10)/5).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, Flow.FromCubicMetersPerSecond(10)/Flow.FromCubicMetersPerSecond(5), CubicMetersPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Flow oneCubicMeterPerSecond = Flow.FromCubicMetersPerSecond(1); - Flow twoCubicMetersPerSecond = Flow.FromCubicMetersPerSecond(2); - - Assert.True(oneCubicMeterPerSecond < twoCubicMetersPerSecond); - Assert.True(oneCubicMeterPerSecond <= twoCubicMetersPerSecond); - Assert.True(twoCubicMetersPerSecond > oneCubicMeterPerSecond); - Assert.True(twoCubicMetersPerSecond >= oneCubicMeterPerSecond); - - Assert.False(oneCubicMeterPerSecond > twoCubicMetersPerSecond); - Assert.False(oneCubicMeterPerSecond >= twoCubicMetersPerSecond); - Assert.False(twoCubicMetersPerSecond < oneCubicMeterPerSecond); - Assert.False(twoCubicMetersPerSecond <= oneCubicMeterPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - Assert.Equal(0, cubicmeterpersecond.CompareTo(cubicmeterpersecond)); - Assert.True(cubicmeterpersecond.CompareTo(Flow.Zero) > 0); - Assert.True(Flow.Zero.CompareTo(cubicmeterpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - Assert.Throws(() => cubicmeterpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - Assert.Throws(() => cubicmeterpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Flow a = Flow.FromCubicMetersPerSecond(1); - Flow b = Flow.FromCubicMetersPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Flow v = Flow.FromCubicMetersPerSecond(1); - Assert.True(v.Equals(Flow.FromCubicMetersPerSecond(1), Flow.FromCubicMetersPerSecond(CubicMetersPerSecondTolerance))); - Assert.False(v.Equals(Flow.Zero, Flow.FromCubicMetersPerSecond(CubicMetersPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - Assert.False(cubicmeterpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Flow cubicmeterpersecond = Flow.FromCubicMetersPerSecond(1); - Assert.False(cubicmeterpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(FlowUnit.Undefined, Flow.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ForceChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ForceChangeRateTestsBase.g.cs deleted file mode 100644 index c7cc526d7e..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ForceChangeRateTestsBase.g.cs +++ /dev/null @@ -1,297 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ForceChangeRate. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ForceChangeRateTestsBase - { - protected abstract double CentinewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double DecanewtonsPerMinuteInOneNewtonPerSecond { get; } - protected abstract double DecanewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double DecinewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double KilonewtonsPerMinuteInOneNewtonPerSecond { get; } - protected abstract double KilonewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double MicronewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double MillinewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double NanonewtonsPerSecondInOneNewtonPerSecond { get; } - protected abstract double NewtonsPerMinuteInOneNewtonPerSecond { get; } - protected abstract double NewtonsPerSecondInOneNewtonPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DecanewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerSecondTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonPerSecondToForceChangeRateUnits() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(CentinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.CentinewtonsPerSecond, CentinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(DecanewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.DecanewtonsPerMinute, DecanewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(DecanewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.DecanewtonsPerSecond, DecanewtonsPerSecondTolerance); - AssertEx.EqualTolerance(DecinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.DecinewtonsPerSecond, DecinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(KilonewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.KilonewtonsPerMinute, KilonewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.KilonewtonsPerSecond, KilonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(MicronewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.MicronewtonsPerSecond, MicronewtonsPerSecondTolerance); - AssertEx.EqualTolerance(MillinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.MillinewtonsPerSecond, MillinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(NanonewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.NanonewtonsPerSecond, NanonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(NewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.NewtonsPerMinute, NewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(NewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.NewtonsPerSecond, NewtonsPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.CentinewtonPerSecond).CentinewtonsPerSecond, CentinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.DecanewtonPerMinute).DecanewtonsPerMinute, DecanewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.DecanewtonPerSecond).DecanewtonsPerSecond, DecanewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.DecinewtonPerSecond).DecinewtonsPerSecond, DecinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.KilonewtonPerMinute).KilonewtonsPerMinute, KilonewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.KilonewtonPerSecond).KilonewtonsPerSecond, KilonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.MicronewtonPerSecond).MicronewtonsPerSecond, MicronewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.MillinewtonPerSecond).MillinewtonsPerSecond, MillinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.NanonewtonPerSecond).NanonewtonsPerSecond, NanonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.NewtonPerMinute).NewtonsPerMinute, NewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.From(1, ForceChangeRateUnit.NewtonPerSecond).NewtonsPerSecond, NewtonsPerSecondTolerance); - } - - [Fact] - public void As() - { - var newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(CentinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.CentinewtonPerSecond), CentinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(DecanewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.DecanewtonPerMinute), DecanewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(DecanewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.DecanewtonPerSecond), DecanewtonsPerSecondTolerance); - AssertEx.EqualTolerance(DecinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.DecinewtonPerSecond), DecinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(KilonewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.KilonewtonPerMinute), KilonewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.KilonewtonPerSecond), KilonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(MicronewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.MicronewtonPerSecond), MicronewtonsPerSecondTolerance); - AssertEx.EqualTolerance(MillinewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.MillinewtonPerSecond), MillinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(NanonewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.NanonewtonPerSecond), NanonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(NewtonsPerMinuteInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.NewtonPerMinute), NewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(NewtonsPerSecondInOneNewtonPerSecond, newtonpersecond.As(ForceChangeRateUnit.NewtonPerSecond), NewtonsPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - - var centinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.CentinewtonPerSecond); - AssertEx.EqualTolerance(CentinewtonsPerSecondInOneNewtonPerSecond, (double)centinewtonpersecondQuantity.Value, CentinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.CentinewtonPerSecond, centinewtonpersecondQuantity.Unit); - - var decanewtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecanewtonPerMinute); - AssertEx.EqualTolerance(DecanewtonsPerMinuteInOneNewtonPerSecond, (double)decanewtonperminuteQuantity.Value, DecanewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerMinute, decanewtonperminuteQuantity.Unit); - - var decanewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecanewtonPerSecond); - AssertEx.EqualTolerance(DecanewtonsPerSecondInOneNewtonPerSecond, (double)decanewtonpersecondQuantity.Value, DecanewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerSecond, decanewtonpersecondQuantity.Unit); - - var decinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.DecinewtonPerSecond); - AssertEx.EqualTolerance(DecinewtonsPerSecondInOneNewtonPerSecond, (double)decinewtonpersecondQuantity.Value, DecinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecinewtonPerSecond, decinewtonpersecondQuantity.Unit); - - var kilonewtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilonewtonPerMinute); - AssertEx.EqualTolerance(KilonewtonsPerMinuteInOneNewtonPerSecond, (double)kilonewtonperminuteQuantity.Value, KilonewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerMinute, kilonewtonperminuteQuantity.Unit); - - var kilonewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.KilonewtonPerSecond); - AssertEx.EqualTolerance(KilonewtonsPerSecondInOneNewtonPerSecond, (double)kilonewtonpersecondQuantity.Value, KilonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerSecond, kilonewtonpersecondQuantity.Unit); - - var micronewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.MicronewtonPerSecond); - AssertEx.EqualTolerance(MicronewtonsPerSecondInOneNewtonPerSecond, (double)micronewtonpersecondQuantity.Value, MicronewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, micronewtonpersecondQuantity.Unit); - - var millinewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.MillinewtonPerSecond); - AssertEx.EqualTolerance(MillinewtonsPerSecondInOneNewtonPerSecond, (double)millinewtonpersecondQuantity.Value, MillinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MillinewtonPerSecond, millinewtonpersecondQuantity.Unit); - - var nanonewtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NanonewtonPerSecond); - AssertEx.EqualTolerance(NanonewtonsPerSecondInOneNewtonPerSecond, (double)nanonewtonpersecondQuantity.Value, NanonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NanonewtonPerSecond, nanonewtonpersecondQuantity.Unit); - - var newtonperminuteQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NewtonPerMinute); - AssertEx.EqualTolerance(NewtonsPerMinuteInOneNewtonPerSecond, (double)newtonperminuteQuantity.Value, NewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerMinute, newtonperminuteQuantity.Unit); - - var newtonpersecondQuantity = newtonpersecond.ToUnit(ForceChangeRateUnit.NewtonPerSecond); - AssertEx.EqualTolerance(NewtonsPerSecondInOneNewtonPerSecond, (double)newtonpersecondQuantity.Value, NewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, newtonpersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(1, ForceChangeRate.FromCentinewtonsPerSecond(newtonpersecond.CentinewtonsPerSecond).NewtonsPerSecond, CentinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecanewtonsPerMinute(newtonpersecond.DecanewtonsPerMinute).NewtonsPerSecond, DecanewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecanewtonsPerSecond(newtonpersecond.DecanewtonsPerSecond).NewtonsPerSecond, DecanewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecinewtonsPerSecond(newtonpersecond.DecinewtonsPerSecond).NewtonsPerSecond, DecinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilonewtonsPerMinute(newtonpersecond.KilonewtonsPerMinute).NewtonsPerSecond, KilonewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilonewtonsPerSecond(newtonpersecond.KilonewtonsPerSecond).NewtonsPerSecond, KilonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromMicronewtonsPerSecond(newtonpersecond.MicronewtonsPerSecond).NewtonsPerSecond, MicronewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromMillinewtonsPerSecond(newtonpersecond.MillinewtonsPerSecond).NewtonsPerSecond, MillinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNanonewtonsPerSecond(newtonpersecond.NanonewtonsPerSecond).NewtonsPerSecond, NanonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNewtonsPerMinute(newtonpersecond.NewtonsPerMinute).NewtonsPerSecond, NewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNewtonsPerSecond(newtonpersecond.NewtonsPerSecond).NewtonsPerSecond, NewtonsPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ForceChangeRate v = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ForceChangeRate.FromNewtonsPerSecond(3)-v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ForceChangeRate.FromNewtonsPerSecond(10)/5).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, ForceChangeRate.FromNewtonsPerSecond(10)/ForceChangeRate.FromNewtonsPerSecond(5), NewtonsPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ForceChangeRate oneNewtonPerSecond = ForceChangeRate.FromNewtonsPerSecond(1); - ForceChangeRate twoNewtonsPerSecond = ForceChangeRate.FromNewtonsPerSecond(2); - - Assert.True(oneNewtonPerSecond < twoNewtonsPerSecond); - Assert.True(oneNewtonPerSecond <= twoNewtonsPerSecond); - Assert.True(twoNewtonsPerSecond > oneNewtonPerSecond); - Assert.True(twoNewtonsPerSecond >= oneNewtonPerSecond); - - Assert.False(oneNewtonPerSecond > twoNewtonsPerSecond); - Assert.False(oneNewtonPerSecond >= twoNewtonsPerSecond); - Assert.False(twoNewtonsPerSecond < oneNewtonPerSecond); - Assert.False(twoNewtonsPerSecond <= oneNewtonPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.Equal(0, newtonpersecond.CompareTo(newtonpersecond)); - Assert.True(newtonpersecond.CompareTo(ForceChangeRate.Zero) > 0); - Assert.True(ForceChangeRate.Zero.CompareTo(newtonpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.Throws(() => newtonpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.Throws(() => newtonpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ForceChangeRate a = ForceChangeRate.FromNewtonsPerSecond(1); - ForceChangeRate b = ForceChangeRate.FromNewtonsPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ForceChangeRate v = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.True(v.Equals(ForceChangeRate.FromNewtonsPerSecond(1), ForceChangeRate.FromNewtonsPerSecond(NewtonsPerSecondTolerance))); - Assert.False(v.Equals(ForceChangeRate.Zero, ForceChangeRate.FromNewtonsPerSecond(NewtonsPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.False(newtonpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.False(newtonpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForceChangeRateUnit.Undefined, ForceChangeRate.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ForcePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ForcePerLengthTestsBase.g.cs deleted file mode 100644 index df43843b85..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ForcePerLengthTestsBase.g.cs +++ /dev/null @@ -1,277 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ForcePerLength. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ForcePerLengthTestsBase - { - protected abstract double CentinewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double DecinewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double KilogramsForcePerMeterInOneNewtonPerMeter { get; } - protected abstract double KilonewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double MeganewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double MicronewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double MillinewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double NanonewtonsPerMeterInOneNewtonPerMeter { get; } - protected abstract double NewtonsPerMeterInOneNewtonPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double DecinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double NanonewtonsPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonPerMeterToForcePerLengthUnits() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(CentinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.CentinewtonsPerMeter, CentinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(DecinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.DecinewtonsPerMeter, DecinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerMeterInOneNewtonPerMeter, newtonpermeter.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.KilonewtonsPerMeter, KilonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MeganewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.MeganewtonsPerMeter, MeganewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MicronewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.MicronewtonsPerMeter, MicronewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MillinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.MillinewtonsPerMeter, MillinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(NanonewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.NanonewtonsPerMeter, NanonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.NewtonsPerMeter, NewtonsPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.CentinewtonPerMeter).CentinewtonsPerMeter, CentinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.DecinewtonPerMeter).DecinewtonsPerMeter, DecinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.KilogramForcePerMeter).KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.KilonewtonPerMeter).KilonewtonsPerMeter, KilonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.MeganewtonPerMeter).MeganewtonsPerMeter, MeganewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.MicronewtonPerMeter).MicronewtonsPerMeter, MicronewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.MillinewtonPerMeter).MillinewtonsPerMeter, MillinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.NanonewtonPerMeter).NanonewtonsPerMeter, NanonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.From(1, ForcePerLengthUnit.NewtonPerMeter).NewtonsPerMeter, NewtonsPerMeterTolerance); - } - - [Fact] - public void As() - { - var newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(CentinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.CentinewtonPerMeter), CentinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(DecinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.DecinewtonPerMeter), DecinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.KilogramForcePerMeter), KilogramsForcePerMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.KilonewtonPerMeter), KilonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MeganewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.MeganewtonPerMeter), MeganewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MicronewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.MicronewtonPerMeter), MicronewtonsPerMeterTolerance); - AssertEx.EqualTolerance(MillinewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.MillinewtonPerMeter), MillinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(NanonewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.NanonewtonPerMeter), NanonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerMeterInOneNewtonPerMeter, newtonpermeter.As(ForcePerLengthUnit.NewtonPerMeter), NewtonsPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - - var centinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.CentinewtonPerMeter); - AssertEx.EqualTolerance(CentinewtonsPerMeterInOneNewtonPerMeter, (double)centinewtonpermeterQuantity.Value, CentinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMeter, centinewtonpermeterQuantity.Unit); - - var decinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.DecinewtonPerMeter); - AssertEx.EqualTolerance(DecinewtonsPerMeterInOneNewtonPerMeter, (double)decinewtonpermeterQuantity.Value, DecinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMeter, decinewtonpermeterQuantity.Unit); - - var kilogramforcepermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilogramForcePerMeter); - AssertEx.EqualTolerance(KilogramsForcePerMeterInOneNewtonPerMeter, (double)kilogramforcepermeterQuantity.Value, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, kilogramforcepermeterQuantity.Unit); - - var kilonewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.KilonewtonPerMeter); - AssertEx.EqualTolerance(KilonewtonsPerMeterInOneNewtonPerMeter, (double)kilonewtonpermeterQuantity.Value, KilonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMeter, kilonewtonpermeterQuantity.Unit); - - var meganewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MeganewtonPerMeter); - AssertEx.EqualTolerance(MeganewtonsPerMeterInOneNewtonPerMeter, (double)meganewtonpermeterQuantity.Value, MeganewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerMeter, meganewtonpermeterQuantity.Unit); - - var micronewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MicronewtonPerMeter); - AssertEx.EqualTolerance(MicronewtonsPerMeterInOneNewtonPerMeter, (double)micronewtonpermeterQuantity.Value, MicronewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, micronewtonpermeterQuantity.Unit); - - var millinewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.MillinewtonPerMeter); - AssertEx.EqualTolerance(MillinewtonsPerMeterInOneNewtonPerMeter, (double)millinewtonpermeterQuantity.Value, MillinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerMeter, millinewtonpermeterQuantity.Unit); - - var nanonewtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NanonewtonPerMeter); - AssertEx.EqualTolerance(NanonewtonsPerMeterInOneNewtonPerMeter, (double)nanonewtonpermeterQuantity.Value, NanonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMeter, nanonewtonpermeterQuantity.Unit); - - var newtonpermeterQuantity = newtonpermeter.ToUnit(ForcePerLengthUnit.NewtonPerMeter); - AssertEx.EqualTolerance(NewtonsPerMeterInOneNewtonPerMeter, (double)newtonpermeterQuantity.Value, NewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, newtonpermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(1, ForcePerLength.FromCentinewtonsPerMeter(newtonpermeter.CentinewtonsPerMeter).NewtonsPerMeter, CentinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecinewtonsPerMeter(newtonpermeter.DecinewtonsPerMeter).NewtonsPerMeter, DecinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilogramsForcePerMeter(newtonpermeter.KilogramsForcePerMeter).NewtonsPerMeter, KilogramsForcePerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilonewtonsPerMeter(newtonpermeter.KilonewtonsPerMeter).NewtonsPerMeter, KilonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMeganewtonsPerMeter(newtonpermeter.MeganewtonsPerMeter).NewtonsPerMeter, MeganewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMicronewtonsPerMeter(newtonpermeter.MicronewtonsPerMeter).NewtonsPerMeter, MicronewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMillinewtonsPerMeter(newtonpermeter.MillinewtonsPerMeter).NewtonsPerMeter, MillinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNanonewtonsPerMeter(newtonpermeter.NanonewtonsPerMeter).NewtonsPerMeter, NanonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNewtonsPerMeter(newtonpermeter.NewtonsPerMeter).NewtonsPerMeter, NewtonsPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ForcePerLength v = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ForcePerLength.FromNewtonsPerMeter(3)-v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ForcePerLength.FromNewtonsPerMeter(10)/5).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, ForcePerLength.FromNewtonsPerMeter(10)/ForcePerLength.FromNewtonsPerMeter(5), NewtonsPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ForcePerLength oneNewtonPerMeter = ForcePerLength.FromNewtonsPerMeter(1); - ForcePerLength twoNewtonsPerMeter = ForcePerLength.FromNewtonsPerMeter(2); - - Assert.True(oneNewtonPerMeter < twoNewtonsPerMeter); - Assert.True(oneNewtonPerMeter <= twoNewtonsPerMeter); - Assert.True(twoNewtonsPerMeter > oneNewtonPerMeter); - Assert.True(twoNewtonsPerMeter >= oneNewtonPerMeter); - - Assert.False(oneNewtonPerMeter > twoNewtonsPerMeter); - Assert.False(oneNewtonPerMeter >= twoNewtonsPerMeter); - Assert.False(twoNewtonsPerMeter < oneNewtonPerMeter); - Assert.False(twoNewtonsPerMeter <= oneNewtonPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - Assert.Equal(0, newtonpermeter.CompareTo(newtonpermeter)); - Assert.True(newtonpermeter.CompareTo(ForcePerLength.Zero) > 0); - Assert.True(ForcePerLength.Zero.CompareTo(newtonpermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - Assert.Throws(() => newtonpermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - Assert.Throws(() => newtonpermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ForcePerLength a = ForcePerLength.FromNewtonsPerMeter(1); - ForcePerLength b = ForcePerLength.FromNewtonsPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ForcePerLength v = ForcePerLength.FromNewtonsPerMeter(1); - Assert.True(v.Equals(ForcePerLength.FromNewtonsPerMeter(1), ForcePerLength.FromNewtonsPerMeter(NewtonsPerMeterTolerance))); - Assert.False(v.Equals(ForcePerLength.Zero, ForcePerLength.FromNewtonsPerMeter(NewtonsPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - Assert.False(newtonpermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - Assert.False(newtonpermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForcePerLengthUnit.Undefined, ForcePerLength.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ForceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ForceTestsBase.g.cs deleted file mode 100644 index ea45f8121a..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ForceTestsBase.g.cs +++ /dev/null @@ -1,317 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Force. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ForceTestsBase - { - protected abstract double DecanewtonsInOneNewton { get; } - protected abstract double DyneInOneNewton { get; } - protected abstract double KilogramsForceInOneNewton { get; } - protected abstract double KilonewtonsInOneNewton { get; } - protected abstract double KiloPondsInOneNewton { get; } - protected abstract double MeganewtonsInOneNewton { get; } - protected abstract double MicronewtonsInOneNewton { get; } - protected abstract double MillinewtonsInOneNewton { get; } - protected abstract double NewtonsInOneNewton { get; } - protected abstract double OunceForceInOneNewton { get; } - protected abstract double PoundalsInOneNewton { get; } - protected abstract double PoundsForceInOneNewton { get; } - protected abstract double TonnesForceInOneNewton { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecanewtonsTolerance { get { return 1e-5; } } - protected virtual double DyneTolerance { get { return 1e-5; } } - protected virtual double KilogramsForceTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsTolerance { get { return 1e-5; } } - protected virtual double KiloPondsTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsTolerance { get { return 1e-5; } } - protected virtual double MicronewtonsTolerance { get { return 1e-5; } } - protected virtual double MillinewtonsTolerance { get { return 1e-5; } } - protected virtual double NewtonsTolerance { get { return 1e-5; } } - protected virtual double OunceForceTolerance { get { return 1e-5; } } - protected virtual double PoundalsTolerance { get { return 1e-5; } } - protected virtual double PoundsForceTolerance { get { return 1e-5; } } - protected virtual double TonnesForceTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonToForceUnits() - { - Force newton = Force.FromNewtons(1); - AssertEx.EqualTolerance(DecanewtonsInOneNewton, newton.Decanewtons, DecanewtonsTolerance); - AssertEx.EqualTolerance(DyneInOneNewton, newton.Dyne, DyneTolerance); - AssertEx.EqualTolerance(KilogramsForceInOneNewton, newton.KilogramsForce, KilogramsForceTolerance); - AssertEx.EqualTolerance(KilonewtonsInOneNewton, newton.Kilonewtons, KilonewtonsTolerance); - AssertEx.EqualTolerance(KiloPondsInOneNewton, newton.KiloPonds, KiloPondsTolerance); - AssertEx.EqualTolerance(MeganewtonsInOneNewton, newton.Meganewtons, MeganewtonsTolerance); - AssertEx.EqualTolerance(MicronewtonsInOneNewton, newton.Micronewtons, MicronewtonsTolerance); - AssertEx.EqualTolerance(MillinewtonsInOneNewton, newton.Millinewtons, MillinewtonsTolerance); - AssertEx.EqualTolerance(NewtonsInOneNewton, newton.Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(OunceForceInOneNewton, newton.OunceForce, OunceForceTolerance); - AssertEx.EqualTolerance(PoundalsInOneNewton, newton.Poundals, PoundalsTolerance); - AssertEx.EqualTolerance(PoundsForceInOneNewton, newton.PoundsForce, PoundsForceTolerance); - AssertEx.EqualTolerance(TonnesForceInOneNewton, newton.TonnesForce, TonnesForceTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Decanewton).Decanewtons, DecanewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Dyn).Dyne, DyneTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.KilogramForce).KilogramsForce, KilogramsForceTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Kilonewton).Kilonewtons, KilonewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.KiloPond).KiloPonds, KiloPondsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Meganewton).Meganewtons, MeganewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Micronewton).Micronewtons, MicronewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Millinewton).Millinewtons, MillinewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Newton).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.OunceForce).OunceForce, OunceForceTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.Poundal).Poundals, PoundalsTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.PoundForce).PoundsForce, PoundsForceTolerance); - AssertEx.EqualTolerance(1, Force.From(1, ForceUnit.TonneForce).TonnesForce, TonnesForceTolerance); - } - - [Fact] - public void As() - { - var newton = Force.FromNewtons(1); - AssertEx.EqualTolerance(DecanewtonsInOneNewton, newton.As(ForceUnit.Decanewton), DecanewtonsTolerance); - AssertEx.EqualTolerance(DyneInOneNewton, newton.As(ForceUnit.Dyn), DyneTolerance); - AssertEx.EqualTolerance(KilogramsForceInOneNewton, newton.As(ForceUnit.KilogramForce), KilogramsForceTolerance); - AssertEx.EqualTolerance(KilonewtonsInOneNewton, newton.As(ForceUnit.Kilonewton), KilonewtonsTolerance); - AssertEx.EqualTolerance(KiloPondsInOneNewton, newton.As(ForceUnit.KiloPond), KiloPondsTolerance); - AssertEx.EqualTolerance(MeganewtonsInOneNewton, newton.As(ForceUnit.Meganewton), MeganewtonsTolerance); - AssertEx.EqualTolerance(MicronewtonsInOneNewton, newton.As(ForceUnit.Micronewton), MicronewtonsTolerance); - AssertEx.EqualTolerance(MillinewtonsInOneNewton, newton.As(ForceUnit.Millinewton), MillinewtonsTolerance); - AssertEx.EqualTolerance(NewtonsInOneNewton, newton.As(ForceUnit.Newton), NewtonsTolerance); - AssertEx.EqualTolerance(OunceForceInOneNewton, newton.As(ForceUnit.OunceForce), OunceForceTolerance); - AssertEx.EqualTolerance(PoundalsInOneNewton, newton.As(ForceUnit.Poundal), PoundalsTolerance); - AssertEx.EqualTolerance(PoundsForceInOneNewton, newton.As(ForceUnit.PoundForce), PoundsForceTolerance); - AssertEx.EqualTolerance(TonnesForceInOneNewton, newton.As(ForceUnit.TonneForce), TonnesForceTolerance); - } - - [Fact] - public void ToUnit() - { - var newton = Force.FromNewtons(1); - - var decanewtonQuantity = newton.ToUnit(ForceUnit.Decanewton); - AssertEx.EqualTolerance(DecanewtonsInOneNewton, (double)decanewtonQuantity.Value, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, decanewtonQuantity.Unit); - - var dynQuantity = newton.ToUnit(ForceUnit.Dyn); - AssertEx.EqualTolerance(DyneInOneNewton, (double)dynQuantity.Value, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, dynQuantity.Unit); - - var kilogramforceQuantity = newton.ToUnit(ForceUnit.KilogramForce); - AssertEx.EqualTolerance(KilogramsForceInOneNewton, (double)kilogramforceQuantity.Value, KilogramsForceTolerance); - Assert.Equal(ForceUnit.KilogramForce, kilogramforceQuantity.Unit); - - var kilonewtonQuantity = newton.ToUnit(ForceUnit.Kilonewton); - AssertEx.EqualTolerance(KilonewtonsInOneNewton, (double)kilonewtonQuantity.Value, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, kilonewtonQuantity.Unit); - - var kilopondQuantity = newton.ToUnit(ForceUnit.KiloPond); - AssertEx.EqualTolerance(KiloPondsInOneNewton, (double)kilopondQuantity.Value, KiloPondsTolerance); - Assert.Equal(ForceUnit.KiloPond, kilopondQuantity.Unit); - - var meganewtonQuantity = newton.ToUnit(ForceUnit.Meganewton); - AssertEx.EqualTolerance(MeganewtonsInOneNewton, (double)meganewtonQuantity.Value, MeganewtonsTolerance); - Assert.Equal(ForceUnit.Meganewton, meganewtonQuantity.Unit); - - var micronewtonQuantity = newton.ToUnit(ForceUnit.Micronewton); - AssertEx.EqualTolerance(MicronewtonsInOneNewton, (double)micronewtonQuantity.Value, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, micronewtonQuantity.Unit); - - var millinewtonQuantity = newton.ToUnit(ForceUnit.Millinewton); - AssertEx.EqualTolerance(MillinewtonsInOneNewton, (double)millinewtonQuantity.Value, MillinewtonsTolerance); - Assert.Equal(ForceUnit.Millinewton, millinewtonQuantity.Unit); - - var newtonQuantity = newton.ToUnit(ForceUnit.Newton); - AssertEx.EqualTolerance(NewtonsInOneNewton, (double)newtonQuantity.Value, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, newtonQuantity.Unit); - - var ounceforceQuantity = newton.ToUnit(ForceUnit.OunceForce); - AssertEx.EqualTolerance(OunceForceInOneNewton, (double)ounceforceQuantity.Value, OunceForceTolerance); - Assert.Equal(ForceUnit.OunceForce, ounceforceQuantity.Unit); - - var poundalQuantity = newton.ToUnit(ForceUnit.Poundal); - AssertEx.EqualTolerance(PoundalsInOneNewton, (double)poundalQuantity.Value, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, poundalQuantity.Unit); - - var poundforceQuantity = newton.ToUnit(ForceUnit.PoundForce); - AssertEx.EqualTolerance(PoundsForceInOneNewton, (double)poundforceQuantity.Value, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, poundforceQuantity.Unit); - - var tonneforceQuantity = newton.ToUnit(ForceUnit.TonneForce); - AssertEx.EqualTolerance(TonnesForceInOneNewton, (double)tonneforceQuantity.Value, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, tonneforceQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Force newton = Force.FromNewtons(1); - AssertEx.EqualTolerance(1, Force.FromDecanewtons(newton.Decanewtons).Newtons, DecanewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromDyne(newton.Dyne).Newtons, DyneTolerance); - AssertEx.EqualTolerance(1, Force.FromKilogramsForce(newton.KilogramsForce).Newtons, KilogramsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromKilonewtons(newton.Kilonewtons).Newtons, KilonewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromKiloPonds(newton.KiloPonds).Newtons, KiloPondsTolerance); - AssertEx.EqualTolerance(1, Force.FromMeganewtons(newton.Meganewtons).Newtons, MeganewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromMicronewtons(newton.Micronewtons).Newtons, MicronewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromMillinewtons(newton.Millinewtons).Newtons, MillinewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromNewtons(newton.Newtons).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromOunceForce(newton.OunceForce).Newtons, OunceForceTolerance); - AssertEx.EqualTolerance(1, Force.FromPoundals(newton.Poundals).Newtons, PoundalsTolerance); - AssertEx.EqualTolerance(1, Force.FromPoundsForce(newton.PoundsForce).Newtons, PoundsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromTonnesForce(newton.TonnesForce).Newtons, TonnesForceTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Force v = Force.FromNewtons(1); - AssertEx.EqualTolerance(-1, -v.Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (Force.FromNewtons(3)-v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (v + v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(10, (v*10).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(10, (10*v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (Force.FromNewtons(10)/5).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, Force.FromNewtons(10)/Force.FromNewtons(5), NewtonsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Force oneNewton = Force.FromNewtons(1); - Force twoNewtons = Force.FromNewtons(2); - - Assert.True(oneNewton < twoNewtons); - Assert.True(oneNewton <= twoNewtons); - Assert.True(twoNewtons > oneNewton); - Assert.True(twoNewtons >= oneNewton); - - Assert.False(oneNewton > twoNewtons); - Assert.False(oneNewton >= twoNewtons); - Assert.False(twoNewtons < oneNewton); - Assert.False(twoNewtons <= oneNewton); - } - - [Fact] - public void CompareToIsImplemented() - { - Force newton = Force.FromNewtons(1); - Assert.Equal(0, newton.CompareTo(newton)); - Assert.True(newton.CompareTo(Force.Zero) > 0); - Assert.True(Force.Zero.CompareTo(newton) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Force newton = Force.FromNewtons(1); - Assert.Throws(() => newton.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Force newton = Force.FromNewtons(1); - Assert.Throws(() => newton.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Force a = Force.FromNewtons(1); - Force b = Force.FromNewtons(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Force v = Force.FromNewtons(1); - Assert.True(v.Equals(Force.FromNewtons(1), Force.FromNewtons(NewtonsTolerance))); - Assert.False(v.Equals(Force.Zero, Force.FromNewtons(NewtonsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Force newton = Force.FromNewtons(1); - Assert.False(newton.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Force newton = Force.FromNewtons(1); - Assert.False(newton.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForceUnit.Undefined, Force.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/FrequencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/FrequencyTestsBase.g.cs deleted file mode 100644 index 095f12058a..0000000000 --- a/UnitsNet.Tests/GeneratedCode/FrequencyTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Frequency. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class FrequencyTestsBase - { - protected abstract double CyclesPerHourInOneHertz { get; } - protected abstract double CyclesPerMinuteInOneHertz { get; } - protected abstract double GigahertzInOneHertz { get; } - protected abstract double HertzInOneHertz { get; } - protected abstract double KilohertzInOneHertz { get; } - protected abstract double MegahertzInOneHertz { get; } - protected abstract double RadiansPerSecondInOneHertz { get; } - protected abstract double TerahertzInOneHertz { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CyclesPerHourTolerance { get { return 1e-5; } } - protected virtual double CyclesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double GigahertzTolerance { get { return 1e-5; } } - protected virtual double HertzTolerance { get { return 1e-5; } } - protected virtual double KilohertzTolerance { get { return 1e-5; } } - protected virtual double MegahertzTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerahertzTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void HertzToFrequencyUnits() - { - Frequency hertz = Frequency.FromHertz(1); - AssertEx.EqualTolerance(CyclesPerHourInOneHertz, hertz.CyclesPerHour, CyclesPerHourTolerance); - AssertEx.EqualTolerance(CyclesPerMinuteInOneHertz, hertz.CyclesPerMinute, CyclesPerMinuteTolerance); - AssertEx.EqualTolerance(GigahertzInOneHertz, hertz.Gigahertz, GigahertzTolerance); - AssertEx.EqualTolerance(HertzInOneHertz, hertz.Hertz, HertzTolerance); - AssertEx.EqualTolerance(KilohertzInOneHertz, hertz.Kilohertz, KilohertzTolerance); - AssertEx.EqualTolerance(MegahertzInOneHertz, hertz.Megahertz, MegahertzTolerance); - AssertEx.EqualTolerance(RadiansPerSecondInOneHertz, hertz.RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(TerahertzInOneHertz, hertz.Terahertz, TerahertzTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.CyclePerHour).CyclesPerHour, CyclesPerHourTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.CyclePerMinute).CyclesPerMinute, CyclesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.Gigahertz).Gigahertz, GigahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.Hertz).Hertz, HertzTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.Kilohertz).Kilohertz, KilohertzTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.Megahertz).Megahertz, MegahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.RadianPerSecond).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, Frequency.From(1, FrequencyUnit.Terahertz).Terahertz, TerahertzTolerance); - } - - [Fact] - public void As() - { - var hertz = Frequency.FromHertz(1); - AssertEx.EqualTolerance(CyclesPerHourInOneHertz, hertz.As(FrequencyUnit.CyclePerHour), CyclesPerHourTolerance); - AssertEx.EqualTolerance(CyclesPerMinuteInOneHertz, hertz.As(FrequencyUnit.CyclePerMinute), CyclesPerMinuteTolerance); - AssertEx.EqualTolerance(GigahertzInOneHertz, hertz.As(FrequencyUnit.Gigahertz), GigahertzTolerance); - AssertEx.EqualTolerance(HertzInOneHertz, hertz.As(FrequencyUnit.Hertz), HertzTolerance); - AssertEx.EqualTolerance(KilohertzInOneHertz, hertz.As(FrequencyUnit.Kilohertz), KilohertzTolerance); - AssertEx.EqualTolerance(MegahertzInOneHertz, hertz.As(FrequencyUnit.Megahertz), MegahertzTolerance); - AssertEx.EqualTolerance(RadiansPerSecondInOneHertz, hertz.As(FrequencyUnit.RadianPerSecond), RadiansPerSecondTolerance); - AssertEx.EqualTolerance(TerahertzInOneHertz, hertz.As(FrequencyUnit.Terahertz), TerahertzTolerance); - } - - [Fact] - public void ToUnit() - { - var hertz = Frequency.FromHertz(1); - - var cycleperhourQuantity = hertz.ToUnit(FrequencyUnit.CyclePerHour); - AssertEx.EqualTolerance(CyclesPerHourInOneHertz, (double)cycleperhourQuantity.Value, CyclesPerHourTolerance); - Assert.Equal(FrequencyUnit.CyclePerHour, cycleperhourQuantity.Unit); - - var cycleperminuteQuantity = hertz.ToUnit(FrequencyUnit.CyclePerMinute); - AssertEx.EqualTolerance(CyclesPerMinuteInOneHertz, (double)cycleperminuteQuantity.Value, CyclesPerMinuteTolerance); - Assert.Equal(FrequencyUnit.CyclePerMinute, cycleperminuteQuantity.Unit); - - var gigahertzQuantity = hertz.ToUnit(FrequencyUnit.Gigahertz); - AssertEx.EqualTolerance(GigahertzInOneHertz, (double)gigahertzQuantity.Value, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, gigahertzQuantity.Unit); - - var hertzQuantity = hertz.ToUnit(FrequencyUnit.Hertz); - AssertEx.EqualTolerance(HertzInOneHertz, (double)hertzQuantity.Value, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, hertzQuantity.Unit); - - var kilohertzQuantity = hertz.ToUnit(FrequencyUnit.Kilohertz); - AssertEx.EqualTolerance(KilohertzInOneHertz, (double)kilohertzQuantity.Value, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, kilohertzQuantity.Unit); - - var megahertzQuantity = hertz.ToUnit(FrequencyUnit.Megahertz); - AssertEx.EqualTolerance(MegahertzInOneHertz, (double)megahertzQuantity.Value, MegahertzTolerance); - Assert.Equal(FrequencyUnit.Megahertz, megahertzQuantity.Unit); - - var radianpersecondQuantity = hertz.ToUnit(FrequencyUnit.RadianPerSecond); - AssertEx.EqualTolerance(RadiansPerSecondInOneHertz, (double)radianpersecondQuantity.Value, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, radianpersecondQuantity.Unit); - - var terahertzQuantity = hertz.ToUnit(FrequencyUnit.Terahertz); - AssertEx.EqualTolerance(TerahertzInOneHertz, (double)terahertzQuantity.Value, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, terahertzQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Frequency hertz = Frequency.FromHertz(1); - AssertEx.EqualTolerance(1, Frequency.FromCyclesPerHour(hertz.CyclesPerHour).Hertz, CyclesPerHourTolerance); - AssertEx.EqualTolerance(1, Frequency.FromCyclesPerMinute(hertz.CyclesPerMinute).Hertz, CyclesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Frequency.FromGigahertz(hertz.Gigahertz).Hertz, GigahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromHertz(hertz.Hertz).Hertz, HertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromKilohertz(hertz.Kilohertz).Hertz, KilohertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromMegahertz(hertz.Megahertz).Hertz, MegahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromRadiansPerSecond(hertz.RadiansPerSecond).Hertz, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, Frequency.FromTerahertz(hertz.Terahertz).Hertz, TerahertzTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Frequency v = Frequency.FromHertz(1); - AssertEx.EqualTolerance(-1, -v.Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (Frequency.FromHertz(3)-v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (v + v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(10, (v*10).Hertz, HertzTolerance); - AssertEx.EqualTolerance(10, (10*v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (Frequency.FromHertz(10)/5).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, Frequency.FromHertz(10)/Frequency.FromHertz(5), HertzTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Frequency oneHertz = Frequency.FromHertz(1); - Frequency twoHertz = Frequency.FromHertz(2); - - Assert.True(oneHertz < twoHertz); - Assert.True(oneHertz <= twoHertz); - Assert.True(twoHertz > oneHertz); - Assert.True(twoHertz >= oneHertz); - - Assert.False(oneHertz > twoHertz); - Assert.False(oneHertz >= twoHertz); - Assert.False(twoHertz < oneHertz); - Assert.False(twoHertz <= oneHertz); - } - - [Fact] - public void CompareToIsImplemented() - { - Frequency hertz = Frequency.FromHertz(1); - Assert.Equal(0, hertz.CompareTo(hertz)); - Assert.True(hertz.CompareTo(Frequency.Zero) > 0); - Assert.True(Frequency.Zero.CompareTo(hertz) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Frequency hertz = Frequency.FromHertz(1); - Assert.Throws(() => hertz.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Frequency hertz = Frequency.FromHertz(1); - Assert.Throws(() => hertz.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Frequency a = Frequency.FromHertz(1); - Frequency b = Frequency.FromHertz(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Frequency v = Frequency.FromHertz(1); - Assert.True(v.Equals(Frequency.FromHertz(1), Frequency.FromHertz(HertzTolerance))); - Assert.False(v.Equals(Frequency.Zero, Frequency.FromHertz(HertzTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Frequency hertz = Frequency.FromHertz(1); - Assert.False(hertz.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Frequency hertz = Frequency.FromHertz(1); - Assert.False(hertz.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(FrequencyUnit.Undefined, Frequency.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/HeatFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/HeatFluxTestsBase.g.cs deleted file mode 100644 index 9ef7210683..0000000000 --- a/UnitsNet.Tests/GeneratedCode/HeatFluxTestsBase.g.cs +++ /dev/null @@ -1,367 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of HeatFlux. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class HeatFluxTestsBase - { - protected abstract double BtusPerHourSquareFootInOneWattPerSquareMeter { get; } - protected abstract double BtusPerMinuteSquareFootInOneWattPerSquareMeter { get; } - protected abstract double BtusPerSecondSquareFootInOneWattPerSquareMeter { get; } - protected abstract double BtusPerSecondSquareInchInOneWattPerSquareMeter { get; } - protected abstract double CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter { get; } - protected abstract double CentiwattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double DeciwattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter { get; } - protected abstract double KilowattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double MicrowattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double MilliwattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double NanowattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double PoundsForcePerFootSecondInOneWattPerSquareMeter { get; } - protected abstract double PoundsPerSecondCubedInOneWattPerSquareMeter { get; } - protected abstract double WattsPerSquareFootInOneWattPerSquareMeter { get; } - protected abstract double WattsPerSquareInchInOneWattPerSquareMeter { get; } - protected abstract double WattsPerSquareMeterInOneWattPerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerHourSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerMinuteSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerSecondSquareFootTolerance { get { return 1e-5; } } - protected virtual double BtusPerSecondSquareInchTolerance { get { return 1e-5; } } - protected virtual double CaloriesPerSecondSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double CentiwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerHourSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerSecondSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerFootSecondTolerance { get { return 1e-5; } } - protected virtual double PoundsPerSecondCubedTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareFootTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareInchTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattPerSquareMeterToHeatFluxUnits() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(BtusPerHourSquareFootInOneWattPerSquareMeter, wattpersquaremeter.BtusPerHourSquareFoot, BtusPerHourSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerMinuteSquareFootInOneWattPerSquareMeter, wattpersquaremeter.BtusPerMinuteSquareFoot, BtusPerMinuteSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerSecondSquareFootInOneWattPerSquareMeter, wattpersquaremeter.BtusPerSecondSquareFoot, BtusPerSecondSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerSecondSquareInchInOneWattPerSquareMeter, wattpersquaremeter.BtusPerSecondSquareInch, BtusPerSecondSquareInchTolerance); - AssertEx.EqualTolerance(CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, wattpersquaremeter.CaloriesPerSecondSquareCentimeter, CaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(CentiwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.CentiwattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(DeciwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.DeciwattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.KilocaloriesPerHourSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - AssertEx.EqualTolerance(KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, wattpersquaremeter.KilocaloriesPerSecondSquareCentimeter, KilocaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MicrowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MilliwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(NanowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(PoundsForcePerFootSecondInOneWattPerSquareMeter, wattpersquaremeter.PoundsForcePerFootSecond, PoundsForcePerFootSecondTolerance); - AssertEx.EqualTolerance(PoundsPerSecondCubedInOneWattPerSquareMeter, wattpersquaremeter.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - AssertEx.EqualTolerance(WattsPerSquareFootInOneWattPerSquareMeter, wattpersquaremeter.WattsPerSquareFoot, WattsPerSquareFootTolerance); - AssertEx.EqualTolerance(WattsPerSquareInchInOneWattPerSquareMeter, wattpersquaremeter.WattsPerSquareInch, WattsPerSquareInchTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.BtuPerHourSquareFoot).BtusPerHourSquareFoot, BtusPerHourSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.BtuPerMinuteSquareFoot).BtusPerMinuteSquareFoot, BtusPerMinuteSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.BtuPerSecondSquareFoot).BtusPerSecondSquareFoot, BtusPerSecondSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.BtuPerSecondSquareInch).BtusPerSecondSquareInch, BtusPerSecondSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.CaloriePerSecondSquareCentimeter).CaloriesPerSecondSquareCentimeter, CaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.CentiwattPerSquareMeter).CentiwattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.DeciwattPerSquareMeter).DeciwattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.KilocaloriePerHourSquareMeter).KilocaloriesPerHourSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter).KilocaloriesPerSecondSquareCentimeter, KilocaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.KilowattPerSquareMeter).KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.MicrowattPerSquareMeter).MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.MilliwattPerSquareMeter).MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.NanowattPerSquareMeter).NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.PoundForcePerFootSecond).PoundsForcePerFootSecond, PoundsForcePerFootSecondTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.PoundPerSecondCubed).PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.WattPerSquareFoot).WattsPerSquareFoot, WattsPerSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.WattPerSquareInch).WattsPerSquareInch, WattsPerSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.From(1, HeatFluxUnit.WattPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(BtusPerHourSquareFootInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.BtuPerHourSquareFoot), BtusPerHourSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerMinuteSquareFootInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.BtuPerMinuteSquareFoot), BtusPerMinuteSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerSecondSquareFootInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.BtuPerSecondSquareFoot), BtusPerSecondSquareFootTolerance); - AssertEx.EqualTolerance(BtusPerSecondSquareInchInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.BtuPerSecondSquareInch), BtusPerSecondSquareInchTolerance); - AssertEx.EqualTolerance(CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.CaloriePerSecondSquareCentimeter), CaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(CentiwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.CentiwattPerSquareMeter), CentiwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(DeciwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.DeciwattPerSquareMeter), DeciwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.KilocaloriePerHourSquareMeter), KilocaloriesPerHourSquareMeterTolerance); - AssertEx.EqualTolerance(KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter), KilocaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.KilowattPerSquareMeter), KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MicrowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.MicrowattPerSquareMeter), MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MilliwattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.MilliwattPerSquareMeter), MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(NanowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.NanowattPerSquareMeter), NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(PoundsForcePerFootSecondInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.PoundForcePerFootSecond), PoundsForcePerFootSecondTolerance); - AssertEx.EqualTolerance(PoundsPerSecondCubedInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.PoundPerSecondCubed), PoundsPerSecondCubedTolerance); - AssertEx.EqualTolerance(WattsPerSquareFootInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.WattPerSquareFoot), WattsPerSquareFootTolerance); - AssertEx.EqualTolerance(WattsPerSquareInchInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.WattPerSquareInch), WattsPerSquareInchTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(HeatFluxUnit.WattPerSquareMeter), WattsPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - - var btuperhoursquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot); - AssertEx.EqualTolerance(BtusPerHourSquareFootInOneWattPerSquareMeter, (double)btuperhoursquarefootQuantity.Value, BtusPerHourSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerHourSquareFoot, btuperhoursquarefootQuantity.Unit); - - var btuperminutesquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot); - AssertEx.EqualTolerance(BtusPerMinuteSquareFootInOneWattPerSquareMeter, (double)btuperminutesquarefootQuantity.Value, BtusPerMinuteSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerMinuteSquareFoot, btuperminutesquarefootQuantity.Unit); - - var btupersecondsquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerSecondSquareFoot); - AssertEx.EqualTolerance(BtusPerSecondSquareFootInOneWattPerSquareMeter, (double)btupersecondsquarefootQuantity.Value, BtusPerSecondSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareFoot, btupersecondsquarefootQuantity.Unit); - - var btupersecondsquareinchQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.BtuPerSecondSquareInch); - AssertEx.EqualTolerance(BtusPerSecondSquareInchInOneWattPerSquareMeter, (double)btupersecondsquareinchQuantity.Value, BtusPerSecondSquareInchTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareInch, btupersecondsquareinchQuantity.Unit); - - var caloriepersecondsquarecentimeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.CaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(CaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, (double)caloriepersecondsquarecentimeterQuantity.Value, CaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.CaloriePerSecondSquareCentimeter, caloriepersecondsquarecentimeterQuantity.Unit); - - var centiwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.CentiwattPerSquareMeter); - AssertEx.EqualTolerance(CentiwattsPerSquareMeterInOneWattPerSquareMeter, (double)centiwattpersquaremeterQuantity.Value, CentiwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.CentiwattPerSquareMeter, centiwattpersquaremeterQuantity.Unit); - - var deciwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.DeciwattPerSquareMeter); - AssertEx.EqualTolerance(DeciwattsPerSquareMeterInOneWattPerSquareMeter, (double)deciwattpersquaremeterQuantity.Value, DeciwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.DeciwattPerSquareMeter, deciwattpersquaremeterQuantity.Unit); - - var kilocalorieperhoursquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilocaloriePerHourSquareMeter); - AssertEx.EqualTolerance(KilocaloriesPerHourSquareMeterInOneWattPerSquareMeter, (double)kilocalorieperhoursquaremeterQuantity.Value, KilocaloriesPerHourSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerHourSquareMeter, kilocalorieperhoursquaremeterQuantity.Unit); - - var kilocaloriepersecondsquarecentimeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(KilocaloriesPerSecondSquareCentimeterInOneWattPerSquareMeter, (double)kilocaloriepersecondsquarecentimeterQuantity.Value, KilocaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, kilocaloriepersecondsquarecentimeterQuantity.Unit); - - var kilowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, (double)kilowattpersquaremeterQuantity.Value, KilowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilowattPerSquareMeter, kilowattpersquaremeterQuantity.Unit); - - var microwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.MicrowattPerSquareMeter); - AssertEx.EqualTolerance(MicrowattsPerSquareMeterInOneWattPerSquareMeter, (double)microwattpersquaremeterQuantity.Value, MicrowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MicrowattPerSquareMeter, microwattpersquaremeterQuantity.Unit); - - var milliwattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.MilliwattPerSquareMeter); - AssertEx.EqualTolerance(MilliwattsPerSquareMeterInOneWattPerSquareMeter, (double)milliwattpersquaremeterQuantity.Value, MilliwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MilliwattPerSquareMeter, milliwattpersquaremeterQuantity.Unit); - - var nanowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.NanowattPerSquareMeter); - AssertEx.EqualTolerance(NanowattsPerSquareMeterInOneWattPerSquareMeter, (double)nanowattpersquaremeterQuantity.Value, NanowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.NanowattPerSquareMeter, nanowattpersquaremeterQuantity.Unit); - - var poundforceperfootsecondQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.PoundForcePerFootSecond); - AssertEx.EqualTolerance(PoundsForcePerFootSecondInOneWattPerSquareMeter, (double)poundforceperfootsecondQuantity.Value, PoundsForcePerFootSecondTolerance); - Assert.Equal(HeatFluxUnit.PoundForcePerFootSecond, poundforceperfootsecondQuantity.Unit); - - var poundpersecondcubedQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.PoundPerSecondCubed); - AssertEx.EqualTolerance(PoundsPerSecondCubedInOneWattPerSquareMeter, (double)poundpersecondcubedQuantity.Value, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, poundpersecondcubedQuantity.Unit); - - var wattpersquarefootQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareFoot); - AssertEx.EqualTolerance(WattsPerSquareFootInOneWattPerSquareMeter, (double)wattpersquarefootQuantity.Value, WattsPerSquareFootTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareFoot, wattpersquarefootQuantity.Unit); - - var wattpersquareinchQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareInch); - AssertEx.EqualTolerance(WattsPerSquareInchInOneWattPerSquareMeter, (double)wattpersquareinchQuantity.Value, WattsPerSquareInchTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareInch, wattpersquareinchQuantity.Unit); - - var wattpersquaremeterQuantity = wattpersquaremeter.ToUnit(HeatFluxUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, (double)wattpersquaremeterQuantity.Value, WattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareMeter, wattpersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerHourSquareFoot(wattpersquaremeter.BtusPerHourSquareFoot).WattsPerSquareMeter, BtusPerHourSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerMinuteSquareFoot(wattpersquaremeter.BtusPerMinuteSquareFoot).WattsPerSquareMeter, BtusPerMinuteSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerSecondSquareFoot(wattpersquaremeter.BtusPerSecondSquareFoot).WattsPerSquareMeter, BtusPerSecondSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerSecondSquareInch(wattpersquaremeter.BtusPerSecondSquareInch).WattsPerSquareMeter, BtusPerSecondSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromCaloriesPerSecondSquareCentimeter(wattpersquaremeter.CaloriesPerSecondSquareCentimeter).WattsPerSquareMeter, CaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromCentiwattsPerSquareMeter(wattpersquaremeter.CentiwattsPerSquareMeter).WattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromDeciwattsPerSquareMeter(wattpersquaremeter.DeciwattsPerSquareMeter).WattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilocaloriesPerHourSquareMeter(wattpersquaremeter.KilocaloriesPerHourSquareMeter).WattsPerSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(wattpersquaremeter.KilocaloriesPerSecondSquareCentimeter).WattsPerSquareMeter, KilocaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromMicrowattsPerSquareMeter(wattpersquaremeter.MicrowattsPerSquareMeter).WattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromMilliwattsPerSquareMeter(wattpersquaremeter.MilliwattsPerSquareMeter).WattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromNanowattsPerSquareMeter(wattpersquaremeter.NanowattsPerSquareMeter).WattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromPoundsForcePerFootSecond(wattpersquaremeter.PoundsForcePerFootSecond).WattsPerSquareMeter, PoundsForcePerFootSecondTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromPoundsPerSecondCubed(wattpersquaremeter.PoundsPerSecondCubed).WattsPerSquareMeter, PoundsPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareFoot(wattpersquaremeter.WattsPerSquareFoot).WattsPerSquareMeter, WattsPerSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareInch(wattpersquaremeter.WattsPerSquareInch).WattsPerSquareMeter, WattsPerSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - HeatFlux v = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (HeatFlux.FromWattsPerSquareMeter(3)-v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (HeatFlux.FromWattsPerSquareMeter(10)/5).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, HeatFlux.FromWattsPerSquareMeter(10)/HeatFlux.FromWattsPerSquareMeter(5), WattsPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - HeatFlux oneWattPerSquareMeter = HeatFlux.FromWattsPerSquareMeter(1); - HeatFlux twoWattsPerSquareMeter = HeatFlux.FromWattsPerSquareMeter(2); - - Assert.True(oneWattPerSquareMeter < twoWattsPerSquareMeter); - Assert.True(oneWattPerSquareMeter <= twoWattsPerSquareMeter); - Assert.True(twoWattsPerSquareMeter > oneWattPerSquareMeter); - Assert.True(twoWattsPerSquareMeter >= oneWattPerSquareMeter); - - Assert.False(oneWattPerSquareMeter > twoWattsPerSquareMeter); - Assert.False(oneWattPerSquareMeter >= twoWattsPerSquareMeter); - Assert.False(twoWattsPerSquareMeter < oneWattPerSquareMeter); - Assert.False(twoWattsPerSquareMeter <= oneWattPerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - Assert.Equal(0, wattpersquaremeter.CompareTo(wattpersquaremeter)); - Assert.True(wattpersquaremeter.CompareTo(HeatFlux.Zero) > 0); - Assert.True(HeatFlux.Zero.CompareTo(wattpersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - Assert.Throws(() => wattpersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - Assert.Throws(() => wattpersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - HeatFlux a = HeatFlux.FromWattsPerSquareMeter(1); - HeatFlux b = HeatFlux.FromWattsPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - HeatFlux v = HeatFlux.FromWattsPerSquareMeter(1); - Assert.True(v.Equals(HeatFlux.FromWattsPerSquareMeter(1), HeatFlux.FromWattsPerSquareMeter(WattsPerSquareMeterTolerance))); - Assert.False(v.Equals(HeatFlux.Zero, HeatFlux.FromWattsPerSquareMeter(WattsPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(HeatFluxUnit.Undefined, HeatFlux.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/HeatTransferCoefficientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/HeatTransferCoefficientTestsBase.g.cs deleted file mode 100644 index 38c513a17a..0000000000 --- a/UnitsNet.Tests/GeneratedCode/HeatTransferCoefficientTestsBase.g.cs +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of HeatTransferCoefficient. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class HeatTransferCoefficientTestsBase - { - protected abstract double WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin { get; } - protected abstract double WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double WattsPerSquareMeterCelsiusTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattPerSquareMeterKelvinToHeatTransferCoefficientUnits() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius).WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - } - - [Fact] - public void As() - { - var wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius), WattsPerSquareMeterCelsiusTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), WattsPerSquareMeterKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - - var wattpersquaremetercelsiusQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, (double)wattpersquaremetercelsiusQuantity.Value, WattsPerSquareMeterCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, wattpersquaremetercelsiusQuantity.Unit); - - var wattpersquaremeterkelvinQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, (double)wattpersquaremeterkelvinQuantity.Value, WattsPerSquareMeterKelvinTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, wattpersquaremeterkelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(wattpersquaremeterkelvin.WattsPerSquareMeterCelsius).WattsPerSquareMeterKelvin, WattsPerSquareMeterCelsiusTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(wattpersquaremeterkelvin.WattsPerSquareMeterKelvin).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - HeatTransferCoefficient v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(3)-v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/5).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(5), WattsPerSquareMeterKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - HeatTransferCoefficient oneWattPerSquareMeterKelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - HeatTransferCoefficient twoWattsPerSquareMeterKelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2); - - Assert.True(oneWattPerSquareMeterKelvin < twoWattsPerSquareMeterKelvin); - Assert.True(oneWattPerSquareMeterKelvin <= twoWattsPerSquareMeterKelvin); - Assert.True(twoWattsPerSquareMeterKelvin > oneWattPerSquareMeterKelvin); - Assert.True(twoWattsPerSquareMeterKelvin >= oneWattPerSquareMeterKelvin); - - Assert.False(oneWattPerSquareMeterKelvin > twoWattsPerSquareMeterKelvin); - Assert.False(oneWattPerSquareMeterKelvin >= twoWattsPerSquareMeterKelvin); - Assert.False(twoWattsPerSquareMeterKelvin < oneWattPerSquareMeterKelvin); - Assert.False(twoWattsPerSquareMeterKelvin <= oneWattPerSquareMeterKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.Equal(0, wattpersquaremeterkelvin.CompareTo(wattpersquaremeterkelvin)); - Assert.True(wattpersquaremeterkelvin.CompareTo(HeatTransferCoefficient.Zero) > 0); - Assert.True(HeatTransferCoefficient.Zero.CompareTo(wattpersquaremeterkelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.Throws(() => wattpersquaremeterkelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.Throws(() => wattpersquaremeterkelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - HeatTransferCoefficient a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - HeatTransferCoefficient b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - HeatTransferCoefficient v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.True(v.Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1), HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(WattsPerSquareMeterKelvinTolerance))); - Assert.False(v.Equals(HeatTransferCoefficient.Zero, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(WattsPerSquareMeterKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.False(wattpersquaremeterkelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.False(wattpersquaremeterkelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(HeatTransferCoefficientUnit.Undefined, HeatTransferCoefficient.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/IlluminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/IlluminanceTestsBase.g.cs deleted file mode 100644 index 19d2830557..0000000000 --- a/UnitsNet.Tests/GeneratedCode/IlluminanceTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Illuminance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class IlluminanceTestsBase - { - protected abstract double KiloluxInOneLux { get; } - protected abstract double LuxInOneLux { get; } - protected abstract double MegaluxInOneLux { get; } - protected abstract double MilliluxInOneLux { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KiloluxTolerance { get { return 1e-5; } } - protected virtual double LuxTolerance { get { return 1e-5; } } - protected virtual double MegaluxTolerance { get { return 1e-5; } } - protected virtual double MilliluxTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void LuxToIlluminanceUnits() - { - Illuminance lux = Illuminance.FromLux(1); - AssertEx.EqualTolerance(KiloluxInOneLux, lux.Kilolux, KiloluxTolerance); - AssertEx.EqualTolerance(LuxInOneLux, lux.Lux, LuxTolerance); - AssertEx.EqualTolerance(MegaluxInOneLux, lux.Megalux, MegaluxTolerance); - AssertEx.EqualTolerance(MilliluxInOneLux, lux.Millilux, MilliluxTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Illuminance.From(1, IlluminanceUnit.Kilolux).Kilolux, KiloluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.From(1, IlluminanceUnit.Lux).Lux, LuxTolerance); - AssertEx.EqualTolerance(1, Illuminance.From(1, IlluminanceUnit.Megalux).Megalux, MegaluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.From(1, IlluminanceUnit.Millilux).Millilux, MilliluxTolerance); - } - - [Fact] - public void As() - { - var lux = Illuminance.FromLux(1); - AssertEx.EqualTolerance(KiloluxInOneLux, lux.As(IlluminanceUnit.Kilolux), KiloluxTolerance); - AssertEx.EqualTolerance(LuxInOneLux, lux.As(IlluminanceUnit.Lux), LuxTolerance); - AssertEx.EqualTolerance(MegaluxInOneLux, lux.As(IlluminanceUnit.Megalux), MegaluxTolerance); - AssertEx.EqualTolerance(MilliluxInOneLux, lux.As(IlluminanceUnit.Millilux), MilliluxTolerance); - } - - [Fact] - public void ToUnit() - { - var lux = Illuminance.FromLux(1); - - var kiloluxQuantity = lux.ToUnit(IlluminanceUnit.Kilolux); - AssertEx.EqualTolerance(KiloluxInOneLux, (double)kiloluxQuantity.Value, KiloluxTolerance); - Assert.Equal(IlluminanceUnit.Kilolux, kiloluxQuantity.Unit); - - var luxQuantity = lux.ToUnit(IlluminanceUnit.Lux); - AssertEx.EqualTolerance(LuxInOneLux, (double)luxQuantity.Value, LuxTolerance); - Assert.Equal(IlluminanceUnit.Lux, luxQuantity.Unit); - - var megaluxQuantity = lux.ToUnit(IlluminanceUnit.Megalux); - AssertEx.EqualTolerance(MegaluxInOneLux, (double)megaluxQuantity.Value, MegaluxTolerance); - Assert.Equal(IlluminanceUnit.Megalux, megaluxQuantity.Unit); - - var milliluxQuantity = lux.ToUnit(IlluminanceUnit.Millilux); - AssertEx.EqualTolerance(MilliluxInOneLux, (double)milliluxQuantity.Value, MilliluxTolerance); - Assert.Equal(IlluminanceUnit.Millilux, milliluxQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Illuminance lux = Illuminance.FromLux(1); - AssertEx.EqualTolerance(1, Illuminance.FromKilolux(lux.Kilolux).Lux, KiloluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromLux(lux.Lux).Lux, LuxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromMegalux(lux.Megalux).Lux, MegaluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromMillilux(lux.Millilux).Lux, MilliluxTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Illuminance v = Illuminance.FromLux(1); - AssertEx.EqualTolerance(-1, -v.Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (Illuminance.FromLux(3)-v).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (v + v).Lux, LuxTolerance); - AssertEx.EqualTolerance(10, (v*10).Lux, LuxTolerance); - AssertEx.EqualTolerance(10, (10*v).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (Illuminance.FromLux(10)/5).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, Illuminance.FromLux(10)/Illuminance.FromLux(5), LuxTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Illuminance oneLux = Illuminance.FromLux(1); - Illuminance twoLux = Illuminance.FromLux(2); - - Assert.True(oneLux < twoLux); - Assert.True(oneLux <= twoLux); - Assert.True(twoLux > oneLux); - Assert.True(twoLux >= oneLux); - - Assert.False(oneLux > twoLux); - Assert.False(oneLux >= twoLux); - Assert.False(twoLux < oneLux); - Assert.False(twoLux <= oneLux); - } - - [Fact] - public void CompareToIsImplemented() - { - Illuminance lux = Illuminance.FromLux(1); - Assert.Equal(0, lux.CompareTo(lux)); - Assert.True(lux.CompareTo(Illuminance.Zero) > 0); - Assert.True(Illuminance.Zero.CompareTo(lux) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Illuminance lux = Illuminance.FromLux(1); - Assert.Throws(() => lux.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Illuminance lux = Illuminance.FromLux(1); - Assert.Throws(() => lux.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Illuminance a = Illuminance.FromLux(1); - Illuminance b = Illuminance.FromLux(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Illuminance v = Illuminance.FromLux(1); - Assert.True(v.Equals(Illuminance.FromLux(1), Illuminance.FromLux(LuxTolerance))); - Assert.False(v.Equals(Illuminance.Zero, Illuminance.FromLux(LuxTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Illuminance lux = Illuminance.FromLux(1); - Assert.False(lux.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Illuminance lux = Illuminance.FromLux(1); - Assert.False(lux.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IlluminanceUnit.Undefined, Illuminance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/InformationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/InformationTestsBase.g.cs index 635c68699f..bab9608cbc 100644 --- a/UnitsNet.Tests/GeneratedCode/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/InformationTestsBase.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -109,6 +108,13 @@ public abstract partial class InformationTestsBase protected virtual double TerabytesTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new Information((decimal)0.0, InformationUnit.Undefined)); + } + + [Fact] public void BitToInformationUnits() { @@ -172,6 +178,7 @@ public void FromValueAndUnit() AssertEx.EqualTolerance(1, Information.From(1, InformationUnit.Terabyte).Terabytes, TerabytesTolerance); } + [Fact] public void As() { @@ -399,28 +406,43 @@ public void CompareToThrowsOnNull() Assert.Throws(() => bit.CompareTo(null)); } - [Fact] public void EqualityOperators() { - Information a = Information.FromBits(1); - Information b = Information.FromBits(2); + var a = Information.FromBits(1); + var b = Information.FromBits(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - Information v = Information.FromBits(1); - Assert.True(v.Equals(Information.FromBits(1), Information.FromBits(BitsTolerance))); - Assert.False(v.Equals(Information.Zero, Information.FromBits(BitsTolerance))); + var a = Information.FromBits(1); + var b = Information.FromBits(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = Information.FromBits(1); + Assert.True(v.Equals(Information.FromBits(1), BitsTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(Information.Zero, BitsTolerance, ComparisonType.Relative)); } [Fact] @@ -443,5 +465,23 @@ 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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(Information.BaseDimensions is null); + } } } diff --git a/UnitsNet.Tests/GeneratedCode/IrradianceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/IrradianceTestsBase.g.cs deleted file mode 100644 index 2fef8007e2..0000000000 --- a/UnitsNet.Tests/GeneratedCode/IrradianceTestsBase.g.cs +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Irradiance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class IrradianceTestsBase - { - protected abstract double KilowattsPerSquareMeterInOneWattPerSquareMeter { get; } - protected abstract double WattsPerSquareMeterInOneWattPerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilowattsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattPerSquareMeterToIrradianceUnits() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Irradiance.From(1, IrradianceUnit.KilowattPerSquareMeter).KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.From(1, IrradianceUnit.WattPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(IrradianceUnit.KilowattPerSquareMeter), KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, wattpersquaremeter.As(IrradianceUnit.WattPerSquareMeter), WattsPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - - var kilowattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(KilowattsPerSquareMeterInOneWattPerSquareMeter, (double)kilowattpersquaremeterQuantity.Value, KilowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareMeter, kilowattpersquaremeterQuantity.Unit); - - var wattpersquaremeterQuantity = wattpersquaremeter.ToUnit(IrradianceUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(WattsPerSquareMeterInOneWattPerSquareMeter, (double)wattpersquaremeterQuantity.Value, WattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareMeter, wattpersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(1, Irradiance.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Irradiance v = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiance.FromWattsPerSquareMeter(3)-v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiance.FromWattsPerSquareMeter(10)/5).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, Irradiance.FromWattsPerSquareMeter(10)/Irradiance.FromWattsPerSquareMeter(5), WattsPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Irradiance oneWattPerSquareMeter = Irradiance.FromWattsPerSquareMeter(1); - Irradiance twoWattsPerSquareMeter = Irradiance.FromWattsPerSquareMeter(2); - - Assert.True(oneWattPerSquareMeter < twoWattsPerSquareMeter); - Assert.True(oneWattPerSquareMeter <= twoWattsPerSquareMeter); - Assert.True(twoWattsPerSquareMeter > oneWattPerSquareMeter); - Assert.True(twoWattsPerSquareMeter >= oneWattPerSquareMeter); - - Assert.False(oneWattPerSquareMeter > twoWattsPerSquareMeter); - Assert.False(oneWattPerSquareMeter >= twoWattsPerSquareMeter); - Assert.False(twoWattsPerSquareMeter < oneWattPerSquareMeter); - Assert.False(twoWattsPerSquareMeter <= oneWattPerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.Equal(0, wattpersquaremeter.CompareTo(wattpersquaremeter)); - Assert.True(wattpersquaremeter.CompareTo(Irradiance.Zero) > 0); - Assert.True(Irradiance.Zero.CompareTo(wattpersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.Throws(() => wattpersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.Throws(() => wattpersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Irradiance a = Irradiance.FromWattsPerSquareMeter(1); - Irradiance b = Irradiance.FromWattsPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Irradiance v = Irradiance.FromWattsPerSquareMeter(1); - Assert.True(v.Equals(Irradiance.FromWattsPerSquareMeter(1), Irradiance.FromWattsPerSquareMeter(WattsPerSquareMeterTolerance))); - Assert.False(v.Equals(Irradiance.Zero, Irradiance.FromWattsPerSquareMeter(WattsPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IrradianceUnit.Undefined, Irradiance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/IrradiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/IrradiationTestsBase.g.cs deleted file mode 100644 index f77c29779f..0000000000 --- a/UnitsNet.Tests/GeneratedCode/IrradiationTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Irradiation. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class IrradiationTestsBase - { - protected abstract double JoulesPerSquareMeterInOneJoulePerSquareMeter { get; } - protected abstract double KilowattHoursPerSquareMeterInOneJoulePerSquareMeter { get; } - protected abstract double WattHoursPerSquareMeterInOneJoulePerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double WattHoursPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerSquareMeterToIrradiationUnits() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(JoulesPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilowattHoursPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.KilowattHoursPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - AssertEx.EqualTolerance(WattHoursPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.WattHoursPerSquareMeter, WattHoursPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Irradiation.From(1, IrradiationUnit.JoulePerSquareMeter).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.From(1, IrradiationUnit.KilowattHourPerSquareMeter).KilowattHoursPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.From(1, IrradiationUnit.WattHourPerSquareMeter).WattHoursPerSquareMeter, WattHoursPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(JoulesPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.As(IrradiationUnit.JoulePerSquareMeter), JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilowattHoursPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.As(IrradiationUnit.KilowattHourPerSquareMeter), KilowattHoursPerSquareMeterTolerance); - AssertEx.EqualTolerance(WattHoursPerSquareMeterInOneJoulePerSquareMeter, joulepersquaremeter.As(IrradiationUnit.WattHourPerSquareMeter), WattHoursPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - - var joulepersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.JoulePerSquareMeter); - AssertEx.EqualTolerance(JoulesPerSquareMeterInOneJoulePerSquareMeter, (double)joulepersquaremeterQuantity.Value, JoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMeter, joulepersquaremeterQuantity.Unit); - - var kilowatthourpersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.KilowattHourPerSquareMeter); - AssertEx.EqualTolerance(KilowattHoursPerSquareMeterInOneJoulePerSquareMeter, (double)kilowatthourpersquaremeterQuantity.Value, KilowattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilowattHourPerSquareMeter, kilowatthourpersquaremeterQuantity.Unit); - - var watthourpersquaremeterQuantity = joulepersquaremeter.ToUnit(IrradiationUnit.WattHourPerSquareMeter); - AssertEx.EqualTolerance(WattHoursPerSquareMeterInOneJoulePerSquareMeter, (double)watthourpersquaremeterQuantity.Value, WattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.WattHourPerSquareMeter, watthourpersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(1, Irradiation.FromJoulesPerSquareMeter(joulepersquaremeter.JoulesPerSquareMeter).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromKilowattHoursPerSquareMeter(joulepersquaremeter.KilowattHoursPerSquareMeter).JoulesPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromWattHoursPerSquareMeter(joulepersquaremeter.WattHoursPerSquareMeter).JoulesPerSquareMeter, WattHoursPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Irradiation v = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiation.FromJoulesPerSquareMeter(3)-v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiation.FromJoulesPerSquareMeter(10)/5).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, Irradiation.FromJoulesPerSquareMeter(10)/Irradiation.FromJoulesPerSquareMeter(5), JoulesPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Irradiation oneJoulePerSquareMeter = Irradiation.FromJoulesPerSquareMeter(1); - Irradiation twoJoulesPerSquareMeter = Irradiation.FromJoulesPerSquareMeter(2); - - Assert.True(oneJoulePerSquareMeter < twoJoulesPerSquareMeter); - Assert.True(oneJoulePerSquareMeter <= twoJoulesPerSquareMeter); - Assert.True(twoJoulesPerSquareMeter > oneJoulePerSquareMeter); - Assert.True(twoJoulesPerSquareMeter >= oneJoulePerSquareMeter); - - Assert.False(oneJoulePerSquareMeter > twoJoulesPerSquareMeter); - Assert.False(oneJoulePerSquareMeter >= twoJoulesPerSquareMeter); - Assert.False(twoJoulesPerSquareMeter < oneJoulePerSquareMeter); - Assert.False(twoJoulesPerSquareMeter <= oneJoulePerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.Equal(0, joulepersquaremeter.CompareTo(joulepersquaremeter)); - Assert.True(joulepersquaremeter.CompareTo(Irradiation.Zero) > 0); - Assert.True(Irradiation.Zero.CompareTo(joulepersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.Throws(() => joulepersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.Throws(() => joulepersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Irradiation a = Irradiation.FromJoulesPerSquareMeter(1); - Irradiation b = Irradiation.FromJoulesPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Irradiation v = Irradiation.FromJoulesPerSquareMeter(1); - Assert.True(v.Equals(Irradiation.FromJoulesPerSquareMeter(1), Irradiation.FromJoulesPerSquareMeter(JoulesPerSquareMeterTolerance))); - Assert.False(v.Equals(Irradiation.Zero, Irradiation.FromJoulesPerSquareMeter(JoulesPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.False(joulepersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.False(joulepersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IrradiationUnit.Undefined, Irradiation.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/KinematicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/KinematicViscosityTestsBase.g.cs deleted file mode 100644 index 1182770b7b..0000000000 --- a/UnitsNet.Tests/GeneratedCode/KinematicViscosityTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of KinematicViscosity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class KinematicViscosityTestsBase - { - protected abstract double CentistokesInOneSquareMeterPerSecond { get; } - protected abstract double DecistokesInOneSquareMeterPerSecond { get; } - protected abstract double KilostokesInOneSquareMeterPerSecond { get; } - protected abstract double MicrostokesInOneSquareMeterPerSecond { get; } - protected abstract double MillistokesInOneSquareMeterPerSecond { get; } - protected abstract double NanostokesInOneSquareMeterPerSecond { get; } - protected abstract double SquareMetersPerSecondInOneSquareMeterPerSecond { get; } - protected abstract double StokesInOneSquareMeterPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentistokesTolerance { get { return 1e-5; } } - protected virtual double DecistokesTolerance { get { return 1e-5; } } - protected virtual double KilostokesTolerance { get { return 1e-5; } } - protected virtual double MicrostokesTolerance { get { return 1e-5; } } - protected virtual double MillistokesTolerance { get { return 1e-5; } } - protected virtual double NanostokesTolerance { get { return 1e-5; } } - protected virtual double SquareMetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double StokesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SquareMeterPerSecondToKinematicViscosityUnits() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(CentistokesInOneSquareMeterPerSecond, squaremeterpersecond.Centistokes, CentistokesTolerance); - AssertEx.EqualTolerance(DecistokesInOneSquareMeterPerSecond, squaremeterpersecond.Decistokes, DecistokesTolerance); - AssertEx.EqualTolerance(KilostokesInOneSquareMeterPerSecond, squaremeterpersecond.Kilostokes, KilostokesTolerance); - AssertEx.EqualTolerance(MicrostokesInOneSquareMeterPerSecond, squaremeterpersecond.Microstokes, MicrostokesTolerance); - AssertEx.EqualTolerance(MillistokesInOneSquareMeterPerSecond, squaremeterpersecond.Millistokes, MillistokesTolerance); - AssertEx.EqualTolerance(NanostokesInOneSquareMeterPerSecond, squaremeterpersecond.Nanostokes, NanostokesTolerance); - AssertEx.EqualTolerance(SquareMetersPerSecondInOneSquareMeterPerSecond, squaremeterpersecond.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(StokesInOneSquareMeterPerSecond, squaremeterpersecond.Stokes, StokesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Centistokes).Centistokes, CentistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Decistokes).Decistokes, DecistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Kilostokes).Kilostokes, KilostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Microstokes).Microstokes, MicrostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Millistokes).Millistokes, MillistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Nanostokes).Nanostokes, NanostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.SquareMeterPerSecond).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.From(1, KinematicViscosityUnit.Stokes).Stokes, StokesTolerance); - } - - [Fact] - public void As() - { - var squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(CentistokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Centistokes), CentistokesTolerance); - AssertEx.EqualTolerance(DecistokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Decistokes), DecistokesTolerance); - AssertEx.EqualTolerance(KilostokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Kilostokes), KilostokesTolerance); - AssertEx.EqualTolerance(MicrostokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Microstokes), MicrostokesTolerance); - AssertEx.EqualTolerance(MillistokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Millistokes), MillistokesTolerance); - AssertEx.EqualTolerance(NanostokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Nanostokes), NanostokesTolerance); - AssertEx.EqualTolerance(SquareMetersPerSecondInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.SquareMeterPerSecond), SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(StokesInOneSquareMeterPerSecond, squaremeterpersecond.As(KinematicViscosityUnit.Stokes), StokesTolerance); - } - - [Fact] - public void ToUnit() - { - var squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - - var centistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Centistokes); - AssertEx.EqualTolerance(CentistokesInOneSquareMeterPerSecond, (double)centistokesQuantity.Value, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, centistokesQuantity.Unit); - - var decistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Decistokes); - AssertEx.EqualTolerance(DecistokesInOneSquareMeterPerSecond, (double)decistokesQuantity.Value, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, decistokesQuantity.Unit); - - var kilostokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Kilostokes); - AssertEx.EqualTolerance(KilostokesInOneSquareMeterPerSecond, (double)kilostokesQuantity.Value, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, kilostokesQuantity.Unit); - - var microstokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Microstokes); - AssertEx.EqualTolerance(MicrostokesInOneSquareMeterPerSecond, (double)microstokesQuantity.Value, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, microstokesQuantity.Unit); - - var millistokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Millistokes); - AssertEx.EqualTolerance(MillistokesInOneSquareMeterPerSecond, (double)millistokesQuantity.Value, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, millistokesQuantity.Unit); - - var nanostokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Nanostokes); - AssertEx.EqualTolerance(NanostokesInOneSquareMeterPerSecond, (double)nanostokesQuantity.Value, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, nanostokesQuantity.Unit); - - var squaremeterpersecondQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond); - AssertEx.EqualTolerance(SquareMetersPerSecondInOneSquareMeterPerSecond, (double)squaremeterpersecondQuantity.Value, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, squaremeterpersecondQuantity.Unit); - - var stokesQuantity = squaremeterpersecond.ToUnit(KinematicViscosityUnit.Stokes); - AssertEx.EqualTolerance(StokesInOneSquareMeterPerSecond, (double)stokesQuantity.Value, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, stokesQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(1, KinematicViscosity.FromCentistokes(squaremeterpersecond.Centistokes).SquareMetersPerSecond, CentistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromDecistokes(squaremeterpersecond.Decistokes).SquareMetersPerSecond, DecistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromKilostokes(squaremeterpersecond.Kilostokes).SquareMetersPerSecond, KilostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromMicrostokes(squaremeterpersecond.Microstokes).SquareMetersPerSecond, MicrostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromMillistokes(squaremeterpersecond.Millistokes).SquareMetersPerSecond, MillistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromNanostokes(squaremeterpersecond.Nanostokes).SquareMetersPerSecond, NanostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromSquareMetersPerSecond(squaremeterpersecond.SquareMetersPerSecond).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromStokes(squaremeterpersecond.Stokes).SquareMetersPerSecond, StokesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - KinematicViscosity v = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (KinematicViscosity.FromSquareMetersPerSecond(3)-v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (KinematicViscosity.FromSquareMetersPerSecond(10)/5).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, KinematicViscosity.FromSquareMetersPerSecond(10)/KinematicViscosity.FromSquareMetersPerSecond(5), SquareMetersPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - KinematicViscosity oneSquareMeterPerSecond = KinematicViscosity.FromSquareMetersPerSecond(1); - KinematicViscosity twoSquareMetersPerSecond = KinematicViscosity.FromSquareMetersPerSecond(2); - - Assert.True(oneSquareMeterPerSecond < twoSquareMetersPerSecond); - Assert.True(oneSquareMeterPerSecond <= twoSquareMetersPerSecond); - Assert.True(twoSquareMetersPerSecond > oneSquareMeterPerSecond); - Assert.True(twoSquareMetersPerSecond >= oneSquareMeterPerSecond); - - Assert.False(oneSquareMeterPerSecond > twoSquareMetersPerSecond); - Assert.False(oneSquareMeterPerSecond >= twoSquareMetersPerSecond); - Assert.False(twoSquareMetersPerSecond < oneSquareMeterPerSecond); - Assert.False(twoSquareMetersPerSecond <= oneSquareMeterPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.Equal(0, squaremeterpersecond.CompareTo(squaremeterpersecond)); - Assert.True(squaremeterpersecond.CompareTo(KinematicViscosity.Zero) > 0); - Assert.True(KinematicViscosity.Zero.CompareTo(squaremeterpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.Throws(() => squaremeterpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.Throws(() => squaremeterpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - KinematicViscosity a = KinematicViscosity.FromSquareMetersPerSecond(1); - KinematicViscosity b = KinematicViscosity.FromSquareMetersPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - KinematicViscosity v = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.True(v.Equals(KinematicViscosity.FromSquareMetersPerSecond(1), KinematicViscosity.FromSquareMetersPerSecond(SquareMetersPerSecondTolerance))); - Assert.False(v.Equals(KinematicViscosity.Zero, KinematicViscosity.FromSquareMetersPerSecond(SquareMetersPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.False(squaremeterpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.False(squaremeterpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(KinematicViscosityUnit.Undefined, KinematicViscosity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/LapseRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LapseRateTestsBase.g.cs deleted file mode 100644 index 10c3f138ff..0000000000 --- a/UnitsNet.Tests/GeneratedCode/LapseRateTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of LapseRate. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class LapseRateTestsBase - { - protected abstract double DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelciusPerKilometerTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DegreeCelsiusPerKilometerToLapseRateUnits() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - AssertEx.EqualTolerance(DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer, degreecelsiusperkilometer.DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, LapseRate.From(1, LapseRateUnit.DegreeCelsiusPerKilometer).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - } - - [Fact] - public void As() - { - var degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - AssertEx.EqualTolerance(DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer, degreecelsiusperkilometer.As(LapseRateUnit.DegreeCelsiusPerKilometer), DegreesCelciusPerKilometerTolerance); - } - - [Fact] - public void ToUnit() - { - var degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - - var degreecelsiusperkilometerQuantity = degreecelsiusperkilometer.ToUnit(LapseRateUnit.DegreeCelsiusPerKilometer); - AssertEx.EqualTolerance(DegreesCelciusPerKilometerInOneDegreeCelsiusPerKilometer, (double)degreecelsiusperkilometerQuantity.Value, DegreesCelciusPerKilometerTolerance); - Assert.Equal(LapseRateUnit.DegreeCelsiusPerKilometer, degreecelsiusperkilometerQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - AssertEx.EqualTolerance(1, LapseRate.FromDegreesCelciusPerKilometer(degreecelsiusperkilometer.DegreesCelciusPerKilometer).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - LapseRate v = LapseRate.FromDegreesCelciusPerKilometer(1); - AssertEx.EqualTolerance(-1, -v.DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(2, (LapseRate.FromDegreesCelciusPerKilometer(3)-v).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(2, (v + v).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(10, (v*10).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(10, (10*v).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(2, (LapseRate.FromDegreesCelciusPerKilometer(10)/5).DegreesCelciusPerKilometer, DegreesCelciusPerKilometerTolerance); - AssertEx.EqualTolerance(2, LapseRate.FromDegreesCelciusPerKilometer(10)/LapseRate.FromDegreesCelciusPerKilometer(5), DegreesCelciusPerKilometerTolerance); - } - - [Fact] - public void ComparisonOperators() - { - LapseRate oneDegreeCelsiusPerKilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - LapseRate twoDegreesCelciusPerKilometer = LapseRate.FromDegreesCelciusPerKilometer(2); - - Assert.True(oneDegreeCelsiusPerKilometer < twoDegreesCelciusPerKilometer); - Assert.True(oneDegreeCelsiusPerKilometer <= twoDegreesCelciusPerKilometer); - Assert.True(twoDegreesCelciusPerKilometer > oneDegreeCelsiusPerKilometer); - Assert.True(twoDegreesCelciusPerKilometer >= oneDegreeCelsiusPerKilometer); - - Assert.False(oneDegreeCelsiusPerKilometer > twoDegreesCelciusPerKilometer); - Assert.False(oneDegreeCelsiusPerKilometer >= twoDegreesCelciusPerKilometer); - Assert.False(twoDegreesCelciusPerKilometer < oneDegreeCelsiusPerKilometer); - Assert.False(twoDegreesCelciusPerKilometer <= oneDegreeCelsiusPerKilometer); - } - - [Fact] - public void CompareToIsImplemented() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.Equal(0, degreecelsiusperkilometer.CompareTo(degreecelsiusperkilometer)); - Assert.True(degreecelsiusperkilometer.CompareTo(LapseRate.Zero) > 0); - Assert.True(LapseRate.Zero.CompareTo(degreecelsiusperkilometer) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.Throws(() => degreecelsiusperkilometer.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.Throws(() => degreecelsiusperkilometer.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - LapseRate a = LapseRate.FromDegreesCelciusPerKilometer(1); - LapseRate b = LapseRate.FromDegreesCelciusPerKilometer(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - LapseRate v = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.True(v.Equals(LapseRate.FromDegreesCelciusPerKilometer(1), LapseRate.FromDegreesCelciusPerKilometer(DegreesCelciusPerKilometerTolerance))); - Assert.False(v.Equals(LapseRate.Zero, LapseRate.FromDegreesCelciusPerKilometer(DegreesCelciusPerKilometerTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.False(degreecelsiusperkilometer.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - LapseRate degreecelsiusperkilometer = LapseRate.FromDegreesCelciusPerKilometer(1); - Assert.False(degreecelsiusperkilometer.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LapseRateUnit.Undefined, LapseRate.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/LengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LengthTestsBase.g.cs index 6db53d0741..18228172a5 100644 --- a/UnitsNet.Tests/GeneratedCode/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/LengthTestsBase.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -101,6 +100,25 @@ public abstract partial class LengthTestsBase protected virtual double YardsTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new Length((double)0.0, LengthUnit.Undefined)); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new Length(double.PositiveInfinity, LengthUnit.Meter)); + Assert.Throws(() => new Length(double.NegativeInfinity, LengthUnit.Meter)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new Length(double.NaN, LengthUnit.Meter)); + } + [Fact] public void MeterToLengthUnits() { @@ -156,6 +174,19 @@ public void FromValueAndUnit() AssertEx.EqualTolerance(1, Length.From(1, LengthUnit.Yard).Yards, YardsTolerance); } + [Fact] + public void FromMeters_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => Length.FromMeters(double.PositiveInfinity)); + Assert.Throws(() => Length.FromMeters(double.NegativeInfinity)); + } + + [Fact] + public void FromMeters_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => Length.FromMeters(double.NaN)); + } + [Fact] public void As() { @@ -359,28 +390,43 @@ public void CompareToThrowsOnNull() Assert.Throws(() => meter.CompareTo(null)); } - [Fact] public void EqualityOperators() { - Length a = Length.FromMeters(1); - Length b = Length.FromMeters(2); + var a = Length.FromMeters(1); + var b = Length.FromMeters(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - Length v = Length.FromMeters(1); - Assert.True(v.Equals(Length.FromMeters(1), Length.FromMeters(MetersTolerance))); - Assert.False(v.Equals(Length.Zero, Length.FromMeters(MetersTolerance))); + var a = Length.FromMeters(1); + var b = Length.FromMeters(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = Length.FromMeters(1); + Assert.True(v.Equals(Length.FromMeters(1), MetersTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(Length.Zero, MetersTolerance, ComparisonType.Relative)); } [Fact] @@ -403,5 +449,23 @@ 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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(Length.BaseDimensions is null); + } } } diff --git a/UnitsNet.Tests/GeneratedCode/LevelTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LevelTestsBase.g.cs index 361a62038e..2f9bfd5f11 100644 --- a/UnitsNet.Tests/GeneratedCode/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/LevelTestsBase.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -61,6 +60,25 @@ public abstract partial class LevelTestsBase protected virtual double NepersTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new Level((double)0.0, LevelUnit.Undefined)); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new Level(double.PositiveInfinity, LevelUnit.Decibel)); + Assert.Throws(() => new Level(double.NegativeInfinity, LevelUnit.Decibel)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new Level(double.NaN, LevelUnit.Decibel)); + } + [Fact] public void DecibelToLevelUnits() { @@ -76,6 +94,19 @@ public void FromValueAndUnit() AssertEx.EqualTolerance(1, Level.From(1, LevelUnit.Neper).Nepers, NepersTolerance); } + [Fact] + public void FromDecibels_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => Level.FromDecibels(double.PositiveInfinity)); + Assert.Throws(() => Level.FromDecibels(double.NegativeInfinity)); + } + + [Fact] + public void FromDecibels_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => Level.FromDecibels(double.NaN)); + } + [Fact] public void As() { @@ -164,28 +195,43 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decibel.CompareTo(null)); } - [Fact] public void EqualityOperators() { - Level a = Level.FromDecibels(1); - Level b = Level.FromDecibels(2); + var a = Level.FromDecibels(1); + var b = Level.FromDecibels(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - Level v = Level.FromDecibels(1); - Assert.True(v.Equals(Level.FromDecibels(1), Level.FromDecibels(DecibelsTolerance))); - Assert.False(v.Equals(Level.Zero, Level.FromDecibels(DecibelsTolerance))); + var a = Level.FromDecibels(1); + var b = Level.FromDecibels(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = Level.FromDecibels(1); + Assert.True(v.Equals(Level.FromDecibels(1), DecibelsTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(Level.Zero, DecibelsTolerance, ComparisonType.Relative)); } [Fact] @@ -208,5 +254,23 @@ 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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(Level.BaseDimensions is null); + } } } diff --git a/UnitsNet.Tests/GeneratedCode/LinearDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LinearDensityTestsBase.g.cs deleted file mode 100644 index 1efda1e3cc..0000000000 --- a/UnitsNet.Tests/GeneratedCode/LinearDensityTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of LinearDensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class LinearDensityTestsBase - { - protected abstract double GramsPerMeterInOneKilogramPerMeter { get; } - protected abstract double KilogramsPerMeterInOneKilogramPerMeter { get; } - protected abstract double PoundsPerFootInOneKilogramPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMeterTolerance { get { return 1e-5; } } - protected virtual double PoundsPerFootTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerMeterToLinearDensityUnits() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(GramsPerMeterInOneKilogramPerMeter, kilogrampermeter.GramsPerMeter, GramsPerMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerMeterInOneKilogramPerMeter, kilogrampermeter.KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(PoundsPerFootInOneKilogramPerMeter, kilogrampermeter.PoundsPerFoot, PoundsPerFootTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, LinearDensity.From(1, LinearDensityUnit.GramPerMeter).GramsPerMeter, GramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.From(1, LinearDensityUnit.KilogramPerMeter).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.From(1, LinearDensityUnit.PoundPerFoot).PoundsPerFoot, PoundsPerFootTolerance); - } - - [Fact] - public void As() - { - var kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(GramsPerMeterInOneKilogramPerMeter, kilogrampermeter.As(LinearDensityUnit.GramPerMeter), GramsPerMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerMeterInOneKilogramPerMeter, kilogrampermeter.As(LinearDensityUnit.KilogramPerMeter), KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(PoundsPerFootInOneKilogramPerMeter, kilogrampermeter.As(LinearDensityUnit.PoundPerFoot), PoundsPerFootTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - - var grampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.GramPerMeter); - AssertEx.EqualTolerance(GramsPerMeterInOneKilogramPerMeter, (double)grampermeterQuantity.Value, GramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMeter, grampermeterQuantity.Unit); - - var kilogrampermeterQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.KilogramPerMeter); - AssertEx.EqualTolerance(KilogramsPerMeterInOneKilogramPerMeter, (double)kilogrampermeterQuantity.Value, KilogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMeter, kilogrampermeterQuantity.Unit); - - var poundperfootQuantity = kilogrampermeter.ToUnit(LinearDensityUnit.PoundPerFoot); - AssertEx.EqualTolerance(PoundsPerFootInOneKilogramPerMeter, (double)poundperfootQuantity.Value, PoundsPerFootTolerance); - Assert.Equal(LinearDensityUnit.PoundPerFoot, poundperfootQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(1, LinearDensity.FromGramsPerMeter(kilogrampermeter.GramsPerMeter).KilogramsPerMeter, GramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromKilogramsPerMeter(kilogrampermeter.KilogramsPerMeter).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromPoundsPerFoot(kilogrampermeter.PoundsPerFoot).KilogramsPerMeter, PoundsPerFootTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - LinearDensity v = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearDensity.FromKilogramsPerMeter(3)-v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearDensity.FromKilogramsPerMeter(10)/5).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, LinearDensity.FromKilogramsPerMeter(10)/LinearDensity.FromKilogramsPerMeter(5), KilogramsPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - LinearDensity oneKilogramPerMeter = LinearDensity.FromKilogramsPerMeter(1); - LinearDensity twoKilogramsPerMeter = LinearDensity.FromKilogramsPerMeter(2); - - Assert.True(oneKilogramPerMeter < twoKilogramsPerMeter); - Assert.True(oneKilogramPerMeter <= twoKilogramsPerMeter); - Assert.True(twoKilogramsPerMeter > oneKilogramPerMeter); - Assert.True(twoKilogramsPerMeter >= oneKilogramPerMeter); - - Assert.False(oneKilogramPerMeter > twoKilogramsPerMeter); - Assert.False(oneKilogramPerMeter >= twoKilogramsPerMeter); - Assert.False(twoKilogramsPerMeter < oneKilogramPerMeter); - Assert.False(twoKilogramsPerMeter <= oneKilogramPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - Assert.Equal(0, kilogrampermeter.CompareTo(kilogrampermeter)); - Assert.True(kilogrampermeter.CompareTo(LinearDensity.Zero) > 0); - Assert.True(LinearDensity.Zero.CompareTo(kilogrampermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - Assert.Throws(() => kilogrampermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - Assert.Throws(() => kilogrampermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - LinearDensity a = LinearDensity.FromKilogramsPerMeter(1); - LinearDensity b = LinearDensity.FromKilogramsPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - LinearDensity v = LinearDensity.FromKilogramsPerMeter(1); - Assert.True(v.Equals(LinearDensity.FromKilogramsPerMeter(1), LinearDensity.FromKilogramsPerMeter(KilogramsPerMeterTolerance))); - Assert.False(v.Equals(LinearDensity.Zero, LinearDensity.FromKilogramsPerMeter(KilogramsPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - Assert.False(kilogrampermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - Assert.False(kilogrampermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LinearDensityUnit.Undefined, LinearDensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/LuminousFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LuminousFluxTestsBase.g.cs deleted file mode 100644 index acc5cbb383..0000000000 --- a/UnitsNet.Tests/GeneratedCode/LuminousFluxTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of LuminousFlux. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class LuminousFluxTestsBase - { - protected abstract double LumensInOneLumen { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double LumensTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void LumenToLuminousFluxUnits() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(LumensInOneLumen, lumen.Lumens, LumensTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, LuminousFlux.From(1, LuminousFluxUnit.Lumen).Lumens, LumensTolerance); - } - - [Fact] - public void As() - { - var lumen = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(LumensInOneLumen, lumen.As(LuminousFluxUnit.Lumen), LumensTolerance); - } - - [Fact] - public void ToUnit() - { - var lumen = LuminousFlux.FromLumens(1); - - var lumenQuantity = lumen.ToUnit(LuminousFluxUnit.Lumen); - AssertEx.EqualTolerance(LumensInOneLumen, (double)lumenQuantity.Value, LumensTolerance); - Assert.Equal(LuminousFluxUnit.Lumen, lumenQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(1, LuminousFlux.FromLumens(lumen.Lumens).Lumens, LumensTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - LuminousFlux v = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(-1, -v.Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (LuminousFlux.FromLumens(3)-v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (v + v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(10, (v*10).Lumens, LumensTolerance); - AssertEx.EqualTolerance(10, (10*v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (LuminousFlux.FromLumens(10)/5).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, LuminousFlux.FromLumens(10)/LuminousFlux.FromLumens(5), LumensTolerance); - } - - [Fact] - public void ComparisonOperators() - { - LuminousFlux oneLumen = LuminousFlux.FromLumens(1); - LuminousFlux twoLumens = LuminousFlux.FromLumens(2); - - Assert.True(oneLumen < twoLumens); - Assert.True(oneLumen <= twoLumens); - Assert.True(twoLumens > oneLumen); - Assert.True(twoLumens >= oneLumen); - - Assert.False(oneLumen > twoLumens); - Assert.False(oneLumen >= twoLumens); - Assert.False(twoLumens < oneLumen); - Assert.False(twoLumens <= oneLumen); - } - - [Fact] - public void CompareToIsImplemented() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.Equal(0, lumen.CompareTo(lumen)); - Assert.True(lumen.CompareTo(LuminousFlux.Zero) > 0); - Assert.True(LuminousFlux.Zero.CompareTo(lumen) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.Throws(() => lumen.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.Throws(() => lumen.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - LuminousFlux a = LuminousFlux.FromLumens(1); - LuminousFlux b = LuminousFlux.FromLumens(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - LuminousFlux v = LuminousFlux.FromLumens(1); - Assert.True(v.Equals(LuminousFlux.FromLumens(1), LuminousFlux.FromLumens(LumensTolerance))); - Assert.False(v.Equals(LuminousFlux.Zero, LuminousFlux.FromLumens(LumensTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.False(lumen.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.False(lumen.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminousFluxUnit.Undefined, LuminousFlux.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/LuminousIntensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/LuminousIntensityTestsBase.g.cs deleted file mode 100644 index 51855d73cc..0000000000 --- a/UnitsNet.Tests/GeneratedCode/LuminousIntensityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of LuminousIntensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class LuminousIntensityTestsBase - { - protected abstract double CandelaInOneCandela { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CandelaTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CandelaToLuminousIntensityUnits() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(CandelaInOneCandela, candela.Candela, CandelaTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, LuminousIntensity.From(1, LuminousIntensityUnit.Candela).Candela, CandelaTolerance); - } - - [Fact] - public void As() - { - var candela = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(CandelaInOneCandela, candela.As(LuminousIntensityUnit.Candela), CandelaTolerance); - } - - [Fact] - public void ToUnit() - { - var candela = LuminousIntensity.FromCandela(1); - - var candelaQuantity = candela.ToUnit(LuminousIntensityUnit.Candela); - AssertEx.EqualTolerance(CandelaInOneCandela, (double)candelaQuantity.Value, CandelaTolerance); - Assert.Equal(LuminousIntensityUnit.Candela, candelaQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(1, LuminousIntensity.FromCandela(candela.Candela).Candela, CandelaTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - LuminousIntensity v = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(-1, -v.Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (LuminousIntensity.FromCandela(3)-v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (v + v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(10, (v*10).Candela, CandelaTolerance); - AssertEx.EqualTolerance(10, (10*v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (LuminousIntensity.FromCandela(10)/5).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, LuminousIntensity.FromCandela(10)/LuminousIntensity.FromCandela(5), CandelaTolerance); - } - - [Fact] - public void ComparisonOperators() - { - LuminousIntensity oneCandela = LuminousIntensity.FromCandela(1); - LuminousIntensity twoCandela = LuminousIntensity.FromCandela(2); - - Assert.True(oneCandela < twoCandela); - Assert.True(oneCandela <= twoCandela); - Assert.True(twoCandela > oneCandela); - Assert.True(twoCandela >= oneCandela); - - Assert.False(oneCandela > twoCandela); - Assert.False(oneCandela >= twoCandela); - Assert.False(twoCandela < oneCandela); - Assert.False(twoCandela <= oneCandela); - } - - [Fact] - public void CompareToIsImplemented() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.Equal(0, candela.CompareTo(candela)); - Assert.True(candela.CompareTo(LuminousIntensity.Zero) > 0); - Assert.True(LuminousIntensity.Zero.CompareTo(candela) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.Throws(() => candela.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.Throws(() => candela.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - LuminousIntensity a = LuminousIntensity.FromCandela(1); - LuminousIntensity b = LuminousIntensity.FromCandela(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - LuminousIntensity v = LuminousIntensity.FromCandela(1); - Assert.True(v.Equals(LuminousIntensity.FromCandela(1), LuminousIntensity.FromCandela(CandelaTolerance))); - Assert.False(v.Equals(LuminousIntensity.Zero, LuminousIntensity.FromCandela(CandelaTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.False(candela.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.False(candela.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminousIntensityUnit.Undefined, LuminousIntensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MagneticFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MagneticFieldTestsBase.g.cs deleted file mode 100644 index 28069bac36..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MagneticFieldTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MagneticField. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MagneticFieldTestsBase - { - protected abstract double MicroteslasInOneTesla { get; } - protected abstract double MilliteslasInOneTesla { get; } - protected abstract double NanoteslasInOneTesla { get; } - protected abstract double TeslasInOneTesla { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double MicroteslasTolerance { get { return 1e-5; } } - protected virtual double MilliteslasTolerance { get { return 1e-5; } } - protected virtual double NanoteslasTolerance { get { return 1e-5; } } - protected virtual double TeslasTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void TeslaToMagneticFieldUnits() - { - MagneticField tesla = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(MicroteslasInOneTesla, tesla.Microteslas, MicroteslasTolerance); - AssertEx.EqualTolerance(MilliteslasInOneTesla, tesla.Milliteslas, MilliteslasTolerance); - AssertEx.EqualTolerance(NanoteslasInOneTesla, tesla.Nanoteslas, NanoteslasTolerance); - AssertEx.EqualTolerance(TeslasInOneTesla, tesla.Teslas, TeslasTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MagneticField.From(1, MagneticFieldUnit.Microtesla).Microteslas, MicroteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.From(1, MagneticFieldUnit.Millitesla).Milliteslas, MilliteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.From(1, MagneticFieldUnit.Nanotesla).Nanoteslas, NanoteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.From(1, MagneticFieldUnit.Tesla).Teslas, TeslasTolerance); - } - - [Fact] - public void As() - { - var tesla = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(MicroteslasInOneTesla, tesla.As(MagneticFieldUnit.Microtesla), MicroteslasTolerance); - AssertEx.EqualTolerance(MilliteslasInOneTesla, tesla.As(MagneticFieldUnit.Millitesla), MilliteslasTolerance); - AssertEx.EqualTolerance(NanoteslasInOneTesla, tesla.As(MagneticFieldUnit.Nanotesla), NanoteslasTolerance); - AssertEx.EqualTolerance(TeslasInOneTesla, tesla.As(MagneticFieldUnit.Tesla), TeslasTolerance); - } - - [Fact] - public void ToUnit() - { - var tesla = MagneticField.FromTeslas(1); - - var microteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Microtesla); - AssertEx.EqualTolerance(MicroteslasInOneTesla, (double)microteslaQuantity.Value, MicroteslasTolerance); - Assert.Equal(MagneticFieldUnit.Microtesla, microteslaQuantity.Unit); - - var milliteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Millitesla); - AssertEx.EqualTolerance(MilliteslasInOneTesla, (double)milliteslaQuantity.Value, MilliteslasTolerance); - Assert.Equal(MagneticFieldUnit.Millitesla, milliteslaQuantity.Unit); - - var nanoteslaQuantity = tesla.ToUnit(MagneticFieldUnit.Nanotesla); - AssertEx.EqualTolerance(NanoteslasInOneTesla, (double)nanoteslaQuantity.Value, NanoteslasTolerance); - Assert.Equal(MagneticFieldUnit.Nanotesla, nanoteslaQuantity.Unit); - - var teslaQuantity = tesla.ToUnit(MagneticFieldUnit.Tesla); - AssertEx.EqualTolerance(TeslasInOneTesla, (double)teslaQuantity.Value, TeslasTolerance); - Assert.Equal(MagneticFieldUnit.Tesla, teslaQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MagneticField tesla = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(1, MagneticField.FromMicroteslas(tesla.Microteslas).Teslas, MicroteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromMilliteslas(tesla.Milliteslas).Teslas, MilliteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromNanoteslas(tesla.Nanoteslas).Teslas, NanoteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromTeslas(tesla.Teslas).Teslas, TeslasTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MagneticField v = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(-1, -v.Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (MagneticField.FromTeslas(3)-v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (v + v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(10, (v*10).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(10, (10*v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (MagneticField.FromTeslas(10)/5).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, MagneticField.FromTeslas(10)/MagneticField.FromTeslas(5), TeslasTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MagneticField oneTesla = MagneticField.FromTeslas(1); - MagneticField twoTeslas = MagneticField.FromTeslas(2); - - Assert.True(oneTesla < twoTeslas); - Assert.True(oneTesla <= twoTeslas); - Assert.True(twoTeslas > oneTesla); - Assert.True(twoTeslas >= oneTesla); - - Assert.False(oneTesla > twoTeslas); - Assert.False(oneTesla >= twoTeslas); - Assert.False(twoTeslas < oneTesla); - Assert.False(twoTeslas <= oneTesla); - } - - [Fact] - public void CompareToIsImplemented() - { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.Equal(0, tesla.CompareTo(tesla)); - Assert.True(tesla.CompareTo(MagneticField.Zero) > 0); - Assert.True(MagneticField.Zero.CompareTo(tesla) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.Throws(() => tesla.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.Throws(() => tesla.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MagneticField a = MagneticField.FromTeslas(1); - MagneticField b = MagneticField.FromTeslas(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MagneticField v = MagneticField.FromTeslas(1); - Assert.True(v.Equals(MagneticField.FromTeslas(1), MagneticField.FromTeslas(TeslasTolerance))); - Assert.False(v.Equals(MagneticField.Zero, MagneticField.FromTeslas(TeslasTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.False(tesla.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.False(tesla.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagneticFieldUnit.Undefined, MagneticField.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MagneticFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MagneticFluxTestsBase.g.cs deleted file mode 100644 index 9a67e75476..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MagneticFluxTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MagneticFlux. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MagneticFluxTestsBase - { - protected abstract double WebersInOneWeber { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double WebersTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WeberToMagneticFluxUnits() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(WebersInOneWeber, weber.Webers, WebersTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MagneticFlux.From(1, MagneticFluxUnit.Weber).Webers, WebersTolerance); - } - - [Fact] - public void As() - { - var weber = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(WebersInOneWeber, weber.As(MagneticFluxUnit.Weber), WebersTolerance); - } - - [Fact] - public void ToUnit() - { - var weber = MagneticFlux.FromWebers(1); - - var weberQuantity = weber.ToUnit(MagneticFluxUnit.Weber); - AssertEx.EqualTolerance(WebersInOneWeber, (double)weberQuantity.Value, WebersTolerance); - Assert.Equal(MagneticFluxUnit.Weber, weberQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(1, MagneticFlux.FromWebers(weber.Webers).Webers, WebersTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MagneticFlux v = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(-1, -v.Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (MagneticFlux.FromWebers(3)-v).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (v + v).Webers, WebersTolerance); - AssertEx.EqualTolerance(10, (v*10).Webers, WebersTolerance); - AssertEx.EqualTolerance(10, (10*v).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (MagneticFlux.FromWebers(10)/5).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, MagneticFlux.FromWebers(10)/MagneticFlux.FromWebers(5), WebersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MagneticFlux oneWeber = MagneticFlux.FromWebers(1); - MagneticFlux twoWebers = MagneticFlux.FromWebers(2); - - Assert.True(oneWeber < twoWebers); - Assert.True(oneWeber <= twoWebers); - Assert.True(twoWebers > oneWeber); - Assert.True(twoWebers >= oneWeber); - - Assert.False(oneWeber > twoWebers); - Assert.False(oneWeber >= twoWebers); - Assert.False(twoWebers < oneWeber); - Assert.False(twoWebers <= oneWeber); - } - - [Fact] - public void CompareToIsImplemented() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.Equal(0, weber.CompareTo(weber)); - Assert.True(weber.CompareTo(MagneticFlux.Zero) > 0); - Assert.True(MagneticFlux.Zero.CompareTo(weber) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.Throws(() => weber.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.Throws(() => weber.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MagneticFlux a = MagneticFlux.FromWebers(1); - MagneticFlux b = MagneticFlux.FromWebers(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MagneticFlux v = MagneticFlux.FromWebers(1); - Assert.True(v.Equals(MagneticFlux.FromWebers(1), MagneticFlux.FromWebers(WebersTolerance))); - Assert.False(v.Equals(MagneticFlux.Zero, MagneticFlux.FromWebers(WebersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.False(weber.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.False(weber.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagneticFluxUnit.Undefined, MagneticFlux.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MagnetizationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MagnetizationTestsBase.g.cs deleted file mode 100644 index 7e3f1aeae2..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MagnetizationTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Magnetization. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MagnetizationTestsBase - { - protected abstract double AmperesPerMeterInOneAmperePerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmperesPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void AmperePerMeterToMagnetizationUnits() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(AmperesPerMeterInOneAmperePerMeter, amperepermeter.AmperesPerMeter, AmperesPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Magnetization.From(1, MagnetizationUnit.AmperePerMeter).AmperesPerMeter, AmperesPerMeterTolerance); - } - - [Fact] - public void As() - { - var amperepermeter = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(AmperesPerMeterInOneAmperePerMeter, amperepermeter.As(MagnetizationUnit.AmperePerMeter), AmperesPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var amperepermeter = Magnetization.FromAmperesPerMeter(1); - - var amperepermeterQuantity = amperepermeter.ToUnit(MagnetizationUnit.AmperePerMeter); - AssertEx.EqualTolerance(AmperesPerMeterInOneAmperePerMeter, (double)amperepermeterQuantity.Value, AmperesPerMeterTolerance); - Assert.Equal(MagnetizationUnit.AmperePerMeter, amperepermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(1, Magnetization.FromAmperesPerMeter(amperepermeter.AmperesPerMeter).AmperesPerMeter, AmperesPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Magnetization v = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Magnetization.FromAmperesPerMeter(3)-v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Magnetization.FromAmperesPerMeter(10)/5).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, Magnetization.FromAmperesPerMeter(10)/Magnetization.FromAmperesPerMeter(5), AmperesPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Magnetization oneAmperePerMeter = Magnetization.FromAmperesPerMeter(1); - Magnetization twoAmperesPerMeter = Magnetization.FromAmperesPerMeter(2); - - Assert.True(oneAmperePerMeter < twoAmperesPerMeter); - Assert.True(oneAmperePerMeter <= twoAmperesPerMeter); - Assert.True(twoAmperesPerMeter > oneAmperePerMeter); - Assert.True(twoAmperesPerMeter >= oneAmperePerMeter); - - Assert.False(oneAmperePerMeter > twoAmperesPerMeter); - Assert.False(oneAmperePerMeter >= twoAmperesPerMeter); - Assert.False(twoAmperesPerMeter < oneAmperePerMeter); - Assert.False(twoAmperesPerMeter <= oneAmperePerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.Equal(0, amperepermeter.CompareTo(amperepermeter)); - Assert.True(amperepermeter.CompareTo(Magnetization.Zero) > 0); - Assert.True(Magnetization.Zero.CompareTo(amperepermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.Throws(() => amperepermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.Throws(() => amperepermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Magnetization a = Magnetization.FromAmperesPerMeter(1); - Magnetization b = Magnetization.FromAmperesPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Magnetization v = Magnetization.FromAmperesPerMeter(1); - Assert.True(v.Equals(Magnetization.FromAmperesPerMeter(1), Magnetization.FromAmperesPerMeter(AmperesPerMeterTolerance))); - Assert.False(v.Equals(Magnetization.Zero, Magnetization.FromAmperesPerMeter(AmperesPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.False(amperepermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.False(amperepermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagnetizationUnit.Undefined, Magnetization.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MassFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MassFlowTestsBase.g.cs index 27746964b6..8df5721ba2 100644 --- a/UnitsNet.Tests/GeneratedCode/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/MassFlowTestsBase.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -93,6 +92,25 @@ public abstract partial class MassFlowTestsBase protected virtual double TonnesPerHourTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new MassFlow((double)0.0, MassFlowUnit.Undefined)); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new MassFlow(double.PositiveInfinity, MassFlowUnit.GramPerSecond)); + Assert.Throws(() => new MassFlow(double.NegativeInfinity, MassFlowUnit.GramPerSecond)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new MassFlow(double.NaN, MassFlowUnit.GramPerSecond)); + } + [Fact] public void GramPerSecondToMassFlowUnits() { @@ -140,6 +158,19 @@ public void FromValueAndUnit() AssertEx.EqualTolerance(1, MassFlow.From(1, MassFlowUnit.TonnePerHour).TonnesPerHour, TonnesPerHourTolerance); } + [Fact] + public void FromGramsPerSecond_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => MassFlow.FromGramsPerSecond(double.PositiveInfinity)); + Assert.Throws(() => MassFlow.FromGramsPerSecond(double.NegativeInfinity)); + } + + [Fact] + public void FromGramsPerSecond_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => MassFlow.FromGramsPerSecond(double.NaN)); + } + [Fact] public void As() { @@ -319,28 +350,43 @@ public void CompareToThrowsOnNull() Assert.Throws(() => grampersecond.CompareTo(null)); } - [Fact] public void EqualityOperators() { - MassFlow a = MassFlow.FromGramsPerSecond(1); - MassFlow b = MassFlow.FromGramsPerSecond(2); + var a = MassFlow.FromGramsPerSecond(1); + var b = MassFlow.FromGramsPerSecond(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - MassFlow v = MassFlow.FromGramsPerSecond(1); - Assert.True(v.Equals(MassFlow.FromGramsPerSecond(1), MassFlow.FromGramsPerSecond(GramsPerSecondTolerance))); - Assert.False(v.Equals(MassFlow.Zero, MassFlow.FromGramsPerSecond(GramsPerSecondTolerance))); + var a = MassFlow.FromGramsPerSecond(1); + var b = MassFlow.FromGramsPerSecond(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = MassFlow.FromGramsPerSecond(1); + Assert.True(v.Equals(MassFlow.FromGramsPerSecond(1), GramsPerSecondTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(MassFlow.Zero, GramsPerSecondTolerance, ComparisonType.Relative)); } [Fact] @@ -363,5 +409,23 @@ 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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(MassFlow.BaseDimensions is null); + } } } diff --git a/UnitsNet.Tests/GeneratedCode/MassFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MassFluxTestsBase.g.cs deleted file mode 100644 index d1a1e0acc2..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MassFluxTestsBase.g.cs +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MassFlux. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MassFluxTestsBase - { - protected abstract double GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter { get; } - protected abstract double KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramsPerSecondPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerSecondPerSquareMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerSecondPerSquareMeterToMassFluxUnits() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MassFlux.From(1, MassFluxUnit.GramPerSecondPerSquareMeter).GramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.From(1, MassFluxUnit.KilogramPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - } - - [Fact] - public void As() - { - var kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeter.As(MassFluxUnit.GramPerSecondPerSquareMeter), GramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeter.As(MassFluxUnit.KilogramPerSecondPerSquareMeter), KilogramsPerSecondPerSquareMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - - var grampersecondpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.GramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(GramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)grampersecondpersquaremeterQuantity.Value, GramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMeter, grampersecondpersquaremeterQuantity.Unit); - - var kilogrampersecondpersquaremeterQuantity = kilogrampersecondpersquaremeter.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(KilogramsPerSecondPerSquareMeterInOneKilogramPerSecondPerSquareMeter, (double)kilogrampersecondpersquaremeterQuantity.Value, KilogramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, kilogrampersecondpersquaremeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MassFlux v = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(3)-v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(10)/5).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, MassFlux.FromKilogramsPerSecondPerSquareMeter(10)/MassFlux.FromKilogramsPerSecondPerSquareMeter(5), KilogramsPerSecondPerSquareMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MassFlux oneKilogramPerSecondPerSquareMeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - MassFlux twoKilogramsPerSecondPerSquareMeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - - Assert.True(oneKilogramPerSecondPerSquareMeter < twoKilogramsPerSecondPerSquareMeter); - Assert.True(oneKilogramPerSecondPerSquareMeter <= twoKilogramsPerSecondPerSquareMeter); - Assert.True(twoKilogramsPerSecondPerSquareMeter > oneKilogramPerSecondPerSquareMeter); - Assert.True(twoKilogramsPerSecondPerSquareMeter >= oneKilogramPerSecondPerSquareMeter); - - Assert.False(oneKilogramPerSecondPerSquareMeter > twoKilogramsPerSecondPerSquareMeter); - Assert.False(oneKilogramPerSecondPerSquareMeter >= twoKilogramsPerSecondPerSquareMeter); - Assert.False(twoKilogramsPerSecondPerSquareMeter < oneKilogramPerSecondPerSquareMeter); - Assert.False(twoKilogramsPerSecondPerSquareMeter <= oneKilogramPerSecondPerSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.Equal(0, kilogrampersecondpersquaremeter.CompareTo(kilogrampersecondpersquaremeter)); - Assert.True(kilogrampersecondpersquaremeter.CompareTo(MassFlux.Zero) > 0); - Assert.True(MassFlux.Zero.CompareTo(kilogrampersecondpersquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.Throws(() => kilogrampersecondpersquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.Throws(() => kilogrampersecondpersquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MassFlux a = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - MassFlux b = MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MassFlux v = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.True(v.Equals(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), MassFlux.FromKilogramsPerSecondPerSquareMeter(KilogramsPerSecondPerSquareMeterTolerance))); - Assert.False(v.Equals(MassFlux.Zero, MassFlux.FromKilogramsPerSecondPerSquareMeter(KilogramsPerSecondPerSquareMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.False(kilogrampersecondpersquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.False(kilogrampersecondpersquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassFluxUnit.Undefined, MassFlux.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MassMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MassMomentOfInertiaTestsBase.g.cs deleted file mode 100644 index c9368b64b7..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MassMomentOfInertiaTestsBase.g.cs +++ /dev/null @@ -1,467 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MassMomentOfInertia. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MassMomentOfInertiaTestsBase - { - protected abstract double GramSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double GramSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double GramSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double GramSquareMillimetersInOneKilogramSquareMeter { get; } - protected abstract double KilogramSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double KilogramSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double KilogramSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double KilogramSquareMillimetersInOneKilogramSquareMeter { get; } - protected abstract double KilotonneSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double KilotonneSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double KilotonneSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double KilotonneSquareMilimetersInOneKilogramSquareMeter { get; } - protected abstract double MegatonneSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double MegatonneSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double MegatonneSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double MegatonneSquareMilimetersInOneKilogramSquareMeter { get; } - protected abstract double MilligramSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double MilligramSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double MilligramSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double MilligramSquareMillimetersInOneKilogramSquareMeter { get; } - protected abstract double PoundSquareFeetInOneKilogramSquareMeter { get; } - protected abstract double PoundSquareInchesInOneKilogramSquareMeter { get; } - protected abstract double SlugSquareFeetInOneKilogramSquareMeter { get; } - protected abstract double SlugSquareInchesInOneKilogramSquareMeter { get; } - protected abstract double TonneSquareCentimetersInOneKilogramSquareMeter { get; } - protected abstract double TonneSquareDecimetersInOneKilogramSquareMeter { get; } - protected abstract double TonneSquareMetersInOneKilogramSquareMeter { get; } - protected abstract double TonneSquareMilimetersInOneKilogramSquareMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double GramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double KilogramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double KilotonneSquareMilimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double MegatonneSquareMilimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareMetersTolerance { get { return 1e-5; } } - protected virtual double MilligramSquareMillimetersTolerance { get { return 1e-5; } } - protected virtual double PoundSquareFeetTolerance { get { return 1e-5; } } - protected virtual double PoundSquareInchesTolerance { get { return 1e-5; } } - protected virtual double SlugSquareFeetTolerance { get { return 1e-5; } } - protected virtual double SlugSquareInchesTolerance { get { return 1e-5; } } - protected virtual double TonneSquareCentimetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareDecimetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareMetersTolerance { get { return 1e-5; } } - protected virtual double TonneSquareMilimetersTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramSquareMeterToMassMomentOfInertiaUnits() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(GramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.GramSquareCentimeters, GramSquareCentimetersTolerance); - AssertEx.EqualTolerance(GramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.GramSquareDecimeters, GramSquareDecimetersTolerance); - AssertEx.EqualTolerance(GramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.GramSquareMeters, GramSquareMetersTolerance); - AssertEx.EqualTolerance(GramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.GramSquareMillimeters, GramSquareMillimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilogramSquareCentimeters, KilogramSquareCentimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilogramSquareDecimeters, KilogramSquareDecimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(KilogramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilogramSquareMillimeters, KilogramSquareMillimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilotonneSquareCentimeters, KilotonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilotonneSquareDecimeters, KilotonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.KilotonneSquareMeters, KilotonneSquareMetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.KilotonneSquareMilimeters, KilotonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.MegatonneSquareCentimeters, MegatonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.MegatonneSquareDecimeters, MegatonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.MegatonneSquareMeters, MegatonneSquareMetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.MegatonneSquareMilimeters, MegatonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.MilligramSquareCentimeters, MilligramSquareCentimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.MilligramSquareDecimeters, MilligramSquareDecimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.MilligramSquareMeters, MilligramSquareMetersTolerance); - AssertEx.EqualTolerance(MilligramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.MilligramSquareMillimeters, MilligramSquareMillimetersTolerance); - AssertEx.EqualTolerance(PoundSquareFeetInOneKilogramSquareMeter, kilogramsquaremeter.PoundSquareFeet, PoundSquareFeetTolerance); - AssertEx.EqualTolerance(PoundSquareInchesInOneKilogramSquareMeter, kilogramsquaremeter.PoundSquareInches, PoundSquareInchesTolerance); - AssertEx.EqualTolerance(SlugSquareFeetInOneKilogramSquareMeter, kilogramsquaremeter.SlugSquareFeet, SlugSquareFeetTolerance); - AssertEx.EqualTolerance(SlugSquareInchesInOneKilogramSquareMeter, kilogramsquaremeter.SlugSquareInches, SlugSquareInchesTolerance); - AssertEx.EqualTolerance(TonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.TonneSquareCentimeters, TonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(TonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.TonneSquareDecimeters, TonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(TonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.TonneSquareMeters, TonneSquareMetersTolerance); - AssertEx.EqualTolerance(TonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.TonneSquareMilimeters, TonneSquareMilimetersTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareCentimeter).GramSquareCentimeters, GramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareDecimeter).GramSquareDecimeters, GramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareMeter).GramSquareMeters, GramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareMillimeter).GramSquareMillimeters, GramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareCentimeter).KilogramSquareCentimeters, KilogramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareDecimeter).KilogramSquareDecimeters, KilogramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareMeter).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareMillimeter).KilogramSquareMillimeters, KilogramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareCentimeter).KilotonneSquareCentimeters, KilotonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareDecimeter).KilotonneSquareDecimeters, KilotonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareMeter).KilotonneSquareMeters, KilotonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareMilimeter).KilotonneSquareMilimeters, KilotonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareCentimeter).MegatonneSquareCentimeters, MegatonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareDecimeter).MegatonneSquareDecimeters, MegatonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareMeter).MegatonneSquareMeters, MegatonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareMilimeter).MegatonneSquareMilimeters, MegatonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareCentimeter).MilligramSquareCentimeters, MilligramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareDecimeter).MilligramSquareDecimeters, MilligramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareMeter).MilligramSquareMeters, MilligramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareMillimeter).MilligramSquareMillimeters, MilligramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.PoundSquareFoot).PoundSquareFeet, PoundSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.PoundSquareInch).PoundSquareInches, PoundSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.SlugSquareFoot).SlugSquareFeet, SlugSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.SlugSquareInch).SlugSquareInches, SlugSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareCentimeter).TonneSquareCentimeters, TonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareDecimeter).TonneSquareDecimeters, TonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareMeter).TonneSquareMeters, TonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareMilimeter).TonneSquareMilimeters, TonneSquareMilimetersTolerance); - } - - [Fact] - public void As() - { - var kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(GramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.GramSquareCentimeter), GramSquareCentimetersTolerance); - AssertEx.EqualTolerance(GramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.GramSquareDecimeter), GramSquareDecimetersTolerance); - AssertEx.EqualTolerance(GramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.GramSquareMeter), GramSquareMetersTolerance); - AssertEx.EqualTolerance(GramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.GramSquareMillimeter), GramSquareMillimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilogramSquareCentimeter), KilogramSquareCentimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilogramSquareDecimeter), KilogramSquareDecimetersTolerance); - AssertEx.EqualTolerance(KilogramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilogramSquareMeter), KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(KilogramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilogramSquareMillimeter), KilogramSquareMillimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter), KilotonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter), KilotonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilotonneSquareMeter), KilotonneSquareMetersTolerance); - AssertEx.EqualTolerance(KilotonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter), KilotonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter), MegatonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter), MegatonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MegatonneSquareMeter), MegatonneSquareMetersTolerance); - AssertEx.EqualTolerance(MegatonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter), MegatonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MilligramSquareCentimeter), MilligramSquareCentimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MilligramSquareDecimeter), MilligramSquareDecimetersTolerance); - AssertEx.EqualTolerance(MilligramSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MilligramSquareMeter), MilligramSquareMetersTolerance); - AssertEx.EqualTolerance(MilligramSquareMillimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.MilligramSquareMillimeter), MilligramSquareMillimetersTolerance); - AssertEx.EqualTolerance(PoundSquareFeetInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.PoundSquareFoot), PoundSquareFeetTolerance); - AssertEx.EqualTolerance(PoundSquareInchesInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.PoundSquareInch), PoundSquareInchesTolerance); - AssertEx.EqualTolerance(SlugSquareFeetInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.SlugSquareFoot), SlugSquareFeetTolerance); - AssertEx.EqualTolerance(SlugSquareInchesInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.SlugSquareInch), SlugSquareInchesTolerance); - AssertEx.EqualTolerance(TonneSquareCentimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.TonneSquareCentimeter), TonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(TonneSquareDecimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.TonneSquareDecimeter), TonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(TonneSquareMetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.TonneSquareMeter), TonneSquareMetersTolerance); - AssertEx.EqualTolerance(TonneSquareMilimetersInOneKilogramSquareMeter, kilogramsquaremeter.As(MassMomentOfInertiaUnit.TonneSquareMilimeter), TonneSquareMilimetersTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - - var gramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareCentimeter); - AssertEx.EqualTolerance(GramSquareCentimetersInOneKilogramSquareMeter, (double)gramsquarecentimeterQuantity.Value, GramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareCentimeter, gramsquarecentimeterQuantity.Unit); - - var gramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareDecimeter); - AssertEx.EqualTolerance(GramSquareDecimetersInOneKilogramSquareMeter, (double)gramsquaredecimeterQuantity.Value, GramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareDecimeter, gramsquaredecimeterQuantity.Unit); - - var gramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareMeter); - AssertEx.EqualTolerance(GramSquareMetersInOneKilogramSquareMeter, (double)gramsquaremeterQuantity.Value, GramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMeter, gramsquaremeterQuantity.Unit); - - var gramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.GramSquareMillimeter); - AssertEx.EqualTolerance(GramSquareMillimetersInOneKilogramSquareMeter, (double)gramsquaremillimeterQuantity.Value, GramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMillimeter, gramsquaremillimeterQuantity.Unit); - - var kilogramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareCentimeter); - AssertEx.EqualTolerance(KilogramSquareCentimetersInOneKilogramSquareMeter, (double)kilogramsquarecentimeterQuantity.Value, KilogramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareCentimeter, kilogramsquarecentimeterQuantity.Unit); - - var kilogramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareDecimeter); - AssertEx.EqualTolerance(KilogramSquareDecimetersInOneKilogramSquareMeter, (double)kilogramsquaredecimeterQuantity.Value, KilogramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareDecimeter, kilogramsquaredecimeterQuantity.Unit); - - var kilogramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter); - AssertEx.EqualTolerance(KilogramSquareMetersInOneKilogramSquareMeter, (double)kilogramsquaremeterQuantity.Value, KilogramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, kilogramsquaremeterQuantity.Unit); - - var kilogramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMillimeter); - AssertEx.EqualTolerance(KilogramSquareMillimetersInOneKilogramSquareMeter, (double)kilogramsquaremillimeterQuantity.Value, KilogramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMillimeter, kilogramsquaremillimeterQuantity.Unit); - - var kilotonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - AssertEx.EqualTolerance(KilotonneSquareCentimetersInOneKilogramSquareMeter, (double)kilotonnesquarecentimeterQuantity.Value, KilotonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, kilotonnesquarecentimeterQuantity.Unit); - - var kilotonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - AssertEx.EqualTolerance(KilotonneSquareDecimetersInOneKilogramSquareMeter, (double)kilotonnesquaredecimeterQuantity.Value, KilotonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, kilotonnesquaredecimeterQuantity.Unit); - - var kilotonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMeter); - AssertEx.EqualTolerance(KilotonneSquareMetersInOneKilogramSquareMeter, (double)kilotonnesquaremeterQuantity.Value, KilotonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMeter, kilotonnesquaremeterQuantity.Unit); - - var kilotonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - AssertEx.EqualTolerance(KilotonneSquareMilimetersInOneKilogramSquareMeter, (double)kilotonnesquaremilimeterQuantity.Value, KilotonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, kilotonnesquaremilimeterQuantity.Unit); - - var megatonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - AssertEx.EqualTolerance(MegatonneSquareCentimetersInOneKilogramSquareMeter, (double)megatonnesquarecentimeterQuantity.Value, MegatonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, megatonnesquarecentimeterQuantity.Unit); - - var megatonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - AssertEx.EqualTolerance(MegatonneSquareDecimetersInOneKilogramSquareMeter, (double)megatonnesquaredecimeterQuantity.Value, MegatonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, megatonnesquaredecimeterQuantity.Unit); - - var megatonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMeter); - AssertEx.EqualTolerance(MegatonneSquareMetersInOneKilogramSquareMeter, (double)megatonnesquaremeterQuantity.Value, MegatonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMeter, megatonnesquaremeterQuantity.Unit); - - var megatonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - AssertEx.EqualTolerance(MegatonneSquareMilimetersInOneKilogramSquareMeter, (double)megatonnesquaremilimeterQuantity.Value, MegatonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, megatonnesquaremilimeterQuantity.Unit); - - var milligramsquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareCentimeter); - AssertEx.EqualTolerance(MilligramSquareCentimetersInOneKilogramSquareMeter, (double)milligramsquarecentimeterQuantity.Value, MilligramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareCentimeter, milligramsquarecentimeterQuantity.Unit); - - var milligramsquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareDecimeter); - AssertEx.EqualTolerance(MilligramSquareDecimetersInOneKilogramSquareMeter, (double)milligramsquaredecimeterQuantity.Value, MilligramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareDecimeter, milligramsquaredecimeterQuantity.Unit); - - var milligramsquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMeter); - AssertEx.EqualTolerance(MilligramSquareMetersInOneKilogramSquareMeter, (double)milligramsquaremeterQuantity.Value, MilligramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMeter, milligramsquaremeterQuantity.Unit); - - var milligramsquaremillimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMillimeter); - AssertEx.EqualTolerance(MilligramSquareMillimetersInOneKilogramSquareMeter, (double)milligramsquaremillimeterQuantity.Value, MilligramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMillimeter, milligramsquaremillimeterQuantity.Unit); - - var poundsquarefootQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.PoundSquareFoot); - AssertEx.EqualTolerance(PoundSquareFeetInOneKilogramSquareMeter, (double)poundsquarefootQuantity.Value, PoundSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareFoot, poundsquarefootQuantity.Unit); - - var poundsquareinchQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.PoundSquareInch); - AssertEx.EqualTolerance(PoundSquareInchesInOneKilogramSquareMeter, (double)poundsquareinchQuantity.Value, PoundSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareInch, poundsquareinchQuantity.Unit); - - var slugsquarefootQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.SlugSquareFoot); - AssertEx.EqualTolerance(SlugSquareFeetInOneKilogramSquareMeter, (double)slugsquarefootQuantity.Value, SlugSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareFoot, slugsquarefootQuantity.Unit); - - var slugsquareinchQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.SlugSquareInch); - AssertEx.EqualTolerance(SlugSquareInchesInOneKilogramSquareMeter, (double)slugsquareinchQuantity.Value, SlugSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareInch, slugsquareinchQuantity.Unit); - - var tonnesquarecentimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareCentimeter); - AssertEx.EqualTolerance(TonneSquareCentimetersInOneKilogramSquareMeter, (double)tonnesquarecentimeterQuantity.Value, TonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareCentimeter, tonnesquarecentimeterQuantity.Unit); - - var tonnesquaredecimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareDecimeter); - AssertEx.EqualTolerance(TonneSquareDecimetersInOneKilogramSquareMeter, (double)tonnesquaredecimeterQuantity.Value, TonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareDecimeter, tonnesquaredecimeterQuantity.Unit); - - var tonnesquaremeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareMeter); - AssertEx.EqualTolerance(TonneSquareMetersInOneKilogramSquareMeter, (double)tonnesquaremeterQuantity.Value, TonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMeter, tonnesquaremeterQuantity.Unit); - - var tonnesquaremilimeterQuantity = kilogramsquaremeter.ToUnit(MassMomentOfInertiaUnit.TonneSquareMilimeter); - AssertEx.EqualTolerance(TonneSquareMilimetersInOneKilogramSquareMeter, (double)tonnesquaremilimeterQuantity.Value, TonneSquareMilimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMilimeter, tonnesquaremilimeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareCentimeters(kilogramsquaremeter.GramSquareCentimeters).KilogramSquareMeters, GramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareDecimeters(kilogramsquaremeter.GramSquareDecimeters).KilogramSquareMeters, GramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareMeters(kilogramsquaremeter.GramSquareMeters).KilogramSquareMeters, GramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareMillimeters(kilogramsquaremeter.GramSquareMillimeters).KilogramSquareMeters, GramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareCentimeters(kilogramsquaremeter.KilogramSquareCentimeters).KilogramSquareMeters, KilogramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareDecimeters(kilogramsquaremeter.KilogramSquareDecimeters).KilogramSquareMeters, KilogramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareMeters(kilogramsquaremeter.KilogramSquareMeters).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareMillimeters(kilogramsquaremeter.KilogramSquareMillimeters).KilogramSquareMeters, KilogramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareCentimeters(kilogramsquaremeter.KilotonneSquareCentimeters).KilogramSquareMeters, KilotonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareDecimeters(kilogramsquaremeter.KilotonneSquareDecimeters).KilogramSquareMeters, KilotonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareMeters(kilogramsquaremeter.KilotonneSquareMeters).KilogramSquareMeters, KilotonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareMilimeters(kilogramsquaremeter.KilotonneSquareMilimeters).KilogramSquareMeters, KilotonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareCentimeters(kilogramsquaremeter.MegatonneSquareCentimeters).KilogramSquareMeters, MegatonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareDecimeters(kilogramsquaremeter.MegatonneSquareDecimeters).KilogramSquareMeters, MegatonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareMeters(kilogramsquaremeter.MegatonneSquareMeters).KilogramSquareMeters, MegatonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareMilimeters(kilogramsquaremeter.MegatonneSquareMilimeters).KilogramSquareMeters, MegatonneSquareMilimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareCentimeters(kilogramsquaremeter.MilligramSquareCentimeters).KilogramSquareMeters, MilligramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareDecimeters(kilogramsquaremeter.MilligramSquareDecimeters).KilogramSquareMeters, MilligramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareMeters(kilogramsquaremeter.MilligramSquareMeters).KilogramSquareMeters, MilligramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareMillimeters(kilogramsquaremeter.MilligramSquareMillimeters).KilogramSquareMeters, MilligramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromPoundSquareFeet(kilogramsquaremeter.PoundSquareFeet).KilogramSquareMeters, PoundSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromPoundSquareInches(kilogramsquaremeter.PoundSquareInches).KilogramSquareMeters, PoundSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromSlugSquareFeet(kilogramsquaremeter.SlugSquareFeet).KilogramSquareMeters, SlugSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromSlugSquareInches(kilogramsquaremeter.SlugSquareInches).KilogramSquareMeters, SlugSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareCentimeters(kilogramsquaremeter.TonneSquareCentimeters).KilogramSquareMeters, TonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareDecimeters(kilogramsquaremeter.TonneSquareDecimeters).KilogramSquareMeters, TonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareMeters(kilogramsquaremeter.TonneSquareMeters).KilogramSquareMeters, TonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareMilimeters(kilogramsquaremeter.TonneSquareMilimeters).KilogramSquareMeters, TonneSquareMilimetersTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MassMomentOfInertia v = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (MassMomentOfInertia.FromKilogramSquareMeters(3)-v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (MassMomentOfInertia.FromKilogramSquareMeters(10)/5).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, MassMomentOfInertia.FromKilogramSquareMeters(10)/MassMomentOfInertia.FromKilogramSquareMeters(5), KilogramSquareMetersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MassMomentOfInertia oneKilogramSquareMeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - MassMomentOfInertia twoKilogramSquareMeters = MassMomentOfInertia.FromKilogramSquareMeters(2); - - Assert.True(oneKilogramSquareMeter < twoKilogramSquareMeters); - Assert.True(oneKilogramSquareMeter <= twoKilogramSquareMeters); - Assert.True(twoKilogramSquareMeters > oneKilogramSquareMeter); - Assert.True(twoKilogramSquareMeters >= oneKilogramSquareMeter); - - Assert.False(oneKilogramSquareMeter > twoKilogramSquareMeters); - Assert.False(oneKilogramSquareMeter >= twoKilogramSquareMeters); - Assert.False(twoKilogramSquareMeters < oneKilogramSquareMeter); - Assert.False(twoKilogramSquareMeters <= oneKilogramSquareMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.Equal(0, kilogramsquaremeter.CompareTo(kilogramsquaremeter)); - Assert.True(kilogramsquaremeter.CompareTo(MassMomentOfInertia.Zero) > 0); - Assert.True(MassMomentOfInertia.Zero.CompareTo(kilogramsquaremeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.Throws(() => kilogramsquaremeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.Throws(() => kilogramsquaremeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MassMomentOfInertia a = MassMomentOfInertia.FromKilogramSquareMeters(1); - MassMomentOfInertia b = MassMomentOfInertia.FromKilogramSquareMeters(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MassMomentOfInertia v = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.True(v.Equals(MassMomentOfInertia.FromKilogramSquareMeters(1), MassMomentOfInertia.FromKilogramSquareMeters(KilogramSquareMetersTolerance))); - Assert.False(v.Equals(MassMomentOfInertia.Zero, MassMomentOfInertia.FromKilogramSquareMeters(KilogramSquareMetersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.False(kilogramsquaremeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.False(kilogramsquaremeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassMomentOfInertiaUnit.Undefined, MassMomentOfInertia.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MassTestsBase.g.cs deleted file mode 100644 index 24f261e8cb..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MassTestsBase.g.cs +++ /dev/null @@ -1,407 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Mass. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MassTestsBase - { - protected abstract double CentigramsInOneKilogram { get; } - protected abstract double DecagramsInOneKilogram { get; } - protected abstract double DecigramsInOneKilogram { get; } - protected abstract double GramsInOneKilogram { get; } - protected abstract double HectogramsInOneKilogram { get; } - protected abstract double KilogramsInOneKilogram { get; } - protected abstract double KilopoundsInOneKilogram { get; } - protected abstract double KilotonnesInOneKilogram { get; } - protected abstract double LongHundredweightInOneKilogram { get; } - protected abstract double LongTonsInOneKilogram { get; } - protected abstract double MegapoundsInOneKilogram { get; } - protected abstract double MegatonnesInOneKilogram { get; } - protected abstract double MicrogramsInOneKilogram { get; } - protected abstract double MilligramsInOneKilogram { get; } - protected abstract double NanogramsInOneKilogram { get; } - protected abstract double OuncesInOneKilogram { get; } - protected abstract double PoundsInOneKilogram { get; } - protected abstract double ShortHundredweightInOneKilogram { get; } - protected abstract double ShortTonsInOneKilogram { get; } - protected abstract double SlugsInOneKilogram { get; } - protected abstract double StoneInOneKilogram { get; } - protected abstract double TonnesInOneKilogram { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsTolerance { get { return 1e-5; } } - protected virtual double DecagramsTolerance { get { return 1e-5; } } - protected virtual double DecigramsTolerance { get { return 1e-5; } } - protected virtual double GramsTolerance { get { return 1e-5; } } - protected virtual double HectogramsTolerance { get { return 1e-5; } } - protected virtual double KilogramsTolerance { get { return 1e-5; } } - protected virtual double KilopoundsTolerance { get { return 1e-5; } } - protected virtual double KilotonnesTolerance { get { return 1e-5; } } - protected virtual double LongHundredweightTolerance { get { return 1e-5; } } - protected virtual double LongTonsTolerance { get { return 1e-5; } } - protected virtual double MegapoundsTolerance { get { return 1e-5; } } - protected virtual double MegatonnesTolerance { get { return 1e-5; } } - protected virtual double MicrogramsTolerance { get { return 1e-5; } } - protected virtual double MilligramsTolerance { get { return 1e-5; } } - protected virtual double NanogramsTolerance { get { return 1e-5; } } - protected virtual double OuncesTolerance { get { return 1e-5; } } - protected virtual double PoundsTolerance { get { return 1e-5; } } - protected virtual double ShortHundredweightTolerance { get { return 1e-5; } } - protected virtual double ShortTonsTolerance { get { return 1e-5; } } - protected virtual double SlugsTolerance { get { return 1e-5; } } - protected virtual double StoneTolerance { get { return 1e-5; } } - protected virtual double TonnesTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramToMassUnits() - { - Mass kilogram = Mass.FromKilograms(1); - AssertEx.EqualTolerance(CentigramsInOneKilogram, kilogram.Centigrams, CentigramsTolerance); - AssertEx.EqualTolerance(DecagramsInOneKilogram, kilogram.Decagrams, DecagramsTolerance); - AssertEx.EqualTolerance(DecigramsInOneKilogram, kilogram.Decigrams, DecigramsTolerance); - AssertEx.EqualTolerance(GramsInOneKilogram, kilogram.Grams, GramsTolerance); - AssertEx.EqualTolerance(HectogramsInOneKilogram, kilogram.Hectograms, HectogramsTolerance); - AssertEx.EqualTolerance(KilogramsInOneKilogram, kilogram.Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(KilopoundsInOneKilogram, kilogram.Kilopounds, KilopoundsTolerance); - AssertEx.EqualTolerance(KilotonnesInOneKilogram, kilogram.Kilotonnes, KilotonnesTolerance); - AssertEx.EqualTolerance(LongHundredweightInOneKilogram, kilogram.LongHundredweight, LongHundredweightTolerance); - AssertEx.EqualTolerance(LongTonsInOneKilogram, kilogram.LongTons, LongTonsTolerance); - AssertEx.EqualTolerance(MegapoundsInOneKilogram, kilogram.Megapounds, MegapoundsTolerance); - AssertEx.EqualTolerance(MegatonnesInOneKilogram, kilogram.Megatonnes, MegatonnesTolerance); - AssertEx.EqualTolerance(MicrogramsInOneKilogram, kilogram.Micrograms, MicrogramsTolerance); - AssertEx.EqualTolerance(MilligramsInOneKilogram, kilogram.Milligrams, MilligramsTolerance); - AssertEx.EqualTolerance(NanogramsInOneKilogram, kilogram.Nanograms, NanogramsTolerance); - AssertEx.EqualTolerance(OuncesInOneKilogram, kilogram.Ounces, OuncesTolerance); - AssertEx.EqualTolerance(PoundsInOneKilogram, kilogram.Pounds, PoundsTolerance); - AssertEx.EqualTolerance(ShortHundredweightInOneKilogram, kilogram.ShortHundredweight, ShortHundredweightTolerance); - AssertEx.EqualTolerance(ShortTonsInOneKilogram, kilogram.ShortTons, ShortTonsTolerance); - AssertEx.EqualTolerance(SlugsInOneKilogram, kilogram.Slugs, SlugsTolerance); - AssertEx.EqualTolerance(StoneInOneKilogram, kilogram.Stone, StoneTolerance); - AssertEx.EqualTolerance(TonnesInOneKilogram, kilogram.Tonnes, TonnesTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Centigram).Centigrams, CentigramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Decagram).Decagrams, DecagramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Decigram).Decigrams, DecigramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Gram).Grams, GramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Hectogram).Hectograms, HectogramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Kilogram).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Kilopound).Kilopounds, KilopoundsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Kilotonne).Kilotonnes, KilotonnesTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.LongHundredweight).LongHundredweight, LongHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.LongTon).LongTons, LongTonsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Megapound).Megapounds, MegapoundsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Megatonne).Megatonnes, MegatonnesTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Microgram).Micrograms, MicrogramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Milligram).Milligrams, MilligramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Nanogram).Nanograms, NanogramsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Ounce).Ounces, OuncesTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Pound).Pounds, PoundsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.ShortHundredweight).ShortHundredweight, ShortHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.ShortTon).ShortTons, ShortTonsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Slug).Slugs, SlugsTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Stone).Stone, StoneTolerance); - AssertEx.EqualTolerance(1, Mass.From(1, MassUnit.Tonne).Tonnes, TonnesTolerance); - } - - [Fact] - public void As() - { - var kilogram = Mass.FromKilograms(1); - AssertEx.EqualTolerance(CentigramsInOneKilogram, kilogram.As(MassUnit.Centigram), CentigramsTolerance); - AssertEx.EqualTolerance(DecagramsInOneKilogram, kilogram.As(MassUnit.Decagram), DecagramsTolerance); - AssertEx.EqualTolerance(DecigramsInOneKilogram, kilogram.As(MassUnit.Decigram), DecigramsTolerance); - AssertEx.EqualTolerance(GramsInOneKilogram, kilogram.As(MassUnit.Gram), GramsTolerance); - AssertEx.EqualTolerance(HectogramsInOneKilogram, kilogram.As(MassUnit.Hectogram), HectogramsTolerance); - AssertEx.EqualTolerance(KilogramsInOneKilogram, kilogram.As(MassUnit.Kilogram), KilogramsTolerance); - AssertEx.EqualTolerance(KilopoundsInOneKilogram, kilogram.As(MassUnit.Kilopound), KilopoundsTolerance); - AssertEx.EqualTolerance(KilotonnesInOneKilogram, kilogram.As(MassUnit.Kilotonne), KilotonnesTolerance); - AssertEx.EqualTolerance(LongHundredweightInOneKilogram, kilogram.As(MassUnit.LongHundredweight), LongHundredweightTolerance); - AssertEx.EqualTolerance(LongTonsInOneKilogram, kilogram.As(MassUnit.LongTon), LongTonsTolerance); - AssertEx.EqualTolerance(MegapoundsInOneKilogram, kilogram.As(MassUnit.Megapound), MegapoundsTolerance); - AssertEx.EqualTolerance(MegatonnesInOneKilogram, kilogram.As(MassUnit.Megatonne), MegatonnesTolerance); - AssertEx.EqualTolerance(MicrogramsInOneKilogram, kilogram.As(MassUnit.Microgram), MicrogramsTolerance); - AssertEx.EqualTolerance(MilligramsInOneKilogram, kilogram.As(MassUnit.Milligram), MilligramsTolerance); - AssertEx.EqualTolerance(NanogramsInOneKilogram, kilogram.As(MassUnit.Nanogram), NanogramsTolerance); - AssertEx.EqualTolerance(OuncesInOneKilogram, kilogram.As(MassUnit.Ounce), OuncesTolerance); - AssertEx.EqualTolerance(PoundsInOneKilogram, kilogram.As(MassUnit.Pound), PoundsTolerance); - AssertEx.EqualTolerance(ShortHundredweightInOneKilogram, kilogram.As(MassUnit.ShortHundredweight), ShortHundredweightTolerance); - AssertEx.EqualTolerance(ShortTonsInOneKilogram, kilogram.As(MassUnit.ShortTon), ShortTonsTolerance); - AssertEx.EqualTolerance(SlugsInOneKilogram, kilogram.As(MassUnit.Slug), SlugsTolerance); - AssertEx.EqualTolerance(StoneInOneKilogram, kilogram.As(MassUnit.Stone), StoneTolerance); - AssertEx.EqualTolerance(TonnesInOneKilogram, kilogram.As(MassUnit.Tonne), TonnesTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogram = Mass.FromKilograms(1); - - var centigramQuantity = kilogram.ToUnit(MassUnit.Centigram); - AssertEx.EqualTolerance(CentigramsInOneKilogram, (double)centigramQuantity.Value, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, centigramQuantity.Unit); - - var decagramQuantity = kilogram.ToUnit(MassUnit.Decagram); - AssertEx.EqualTolerance(DecagramsInOneKilogram, (double)decagramQuantity.Value, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, decagramQuantity.Unit); - - var decigramQuantity = kilogram.ToUnit(MassUnit.Decigram); - AssertEx.EqualTolerance(DecigramsInOneKilogram, (double)decigramQuantity.Value, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, decigramQuantity.Unit); - - var gramQuantity = kilogram.ToUnit(MassUnit.Gram); - AssertEx.EqualTolerance(GramsInOneKilogram, (double)gramQuantity.Value, GramsTolerance); - Assert.Equal(MassUnit.Gram, gramQuantity.Unit); - - var hectogramQuantity = kilogram.ToUnit(MassUnit.Hectogram); - AssertEx.EqualTolerance(HectogramsInOneKilogram, (double)hectogramQuantity.Value, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, hectogramQuantity.Unit); - - var kilogramQuantity = kilogram.ToUnit(MassUnit.Kilogram); - AssertEx.EqualTolerance(KilogramsInOneKilogram, (double)kilogramQuantity.Value, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, kilogramQuantity.Unit); - - var kilopoundQuantity = kilogram.ToUnit(MassUnit.Kilopound); - AssertEx.EqualTolerance(KilopoundsInOneKilogram, (double)kilopoundQuantity.Value, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, kilopoundQuantity.Unit); - - var kilotonneQuantity = kilogram.ToUnit(MassUnit.Kilotonne); - AssertEx.EqualTolerance(KilotonnesInOneKilogram, (double)kilotonneQuantity.Value, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, kilotonneQuantity.Unit); - - var longhundredweightQuantity = kilogram.ToUnit(MassUnit.LongHundredweight); - AssertEx.EqualTolerance(LongHundredweightInOneKilogram, (double)longhundredweightQuantity.Value, LongHundredweightTolerance); - Assert.Equal(MassUnit.LongHundredweight, longhundredweightQuantity.Unit); - - var longtonQuantity = kilogram.ToUnit(MassUnit.LongTon); - AssertEx.EqualTolerance(LongTonsInOneKilogram, (double)longtonQuantity.Value, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, longtonQuantity.Unit); - - var megapoundQuantity = kilogram.ToUnit(MassUnit.Megapound); - AssertEx.EqualTolerance(MegapoundsInOneKilogram, (double)megapoundQuantity.Value, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, megapoundQuantity.Unit); - - var megatonneQuantity = kilogram.ToUnit(MassUnit.Megatonne); - AssertEx.EqualTolerance(MegatonnesInOneKilogram, (double)megatonneQuantity.Value, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, megatonneQuantity.Unit); - - var microgramQuantity = kilogram.ToUnit(MassUnit.Microgram); - AssertEx.EqualTolerance(MicrogramsInOneKilogram, (double)microgramQuantity.Value, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, microgramQuantity.Unit); - - var milligramQuantity = kilogram.ToUnit(MassUnit.Milligram); - AssertEx.EqualTolerance(MilligramsInOneKilogram, (double)milligramQuantity.Value, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, milligramQuantity.Unit); - - var nanogramQuantity = kilogram.ToUnit(MassUnit.Nanogram); - AssertEx.EqualTolerance(NanogramsInOneKilogram, (double)nanogramQuantity.Value, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, nanogramQuantity.Unit); - - var ounceQuantity = kilogram.ToUnit(MassUnit.Ounce); - AssertEx.EqualTolerance(OuncesInOneKilogram, (double)ounceQuantity.Value, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, ounceQuantity.Unit); - - var poundQuantity = kilogram.ToUnit(MassUnit.Pound); - AssertEx.EqualTolerance(PoundsInOneKilogram, (double)poundQuantity.Value, PoundsTolerance); - Assert.Equal(MassUnit.Pound, poundQuantity.Unit); - - var shorthundredweightQuantity = kilogram.ToUnit(MassUnit.ShortHundredweight); - AssertEx.EqualTolerance(ShortHundredweightInOneKilogram, (double)shorthundredweightQuantity.Value, ShortHundredweightTolerance); - Assert.Equal(MassUnit.ShortHundredweight, shorthundredweightQuantity.Unit); - - var shorttonQuantity = kilogram.ToUnit(MassUnit.ShortTon); - AssertEx.EqualTolerance(ShortTonsInOneKilogram, (double)shorttonQuantity.Value, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, shorttonQuantity.Unit); - - var slugQuantity = kilogram.ToUnit(MassUnit.Slug); - AssertEx.EqualTolerance(SlugsInOneKilogram, (double)slugQuantity.Value, SlugsTolerance); - Assert.Equal(MassUnit.Slug, slugQuantity.Unit); - - var stoneQuantity = kilogram.ToUnit(MassUnit.Stone); - AssertEx.EqualTolerance(StoneInOneKilogram, (double)stoneQuantity.Value, StoneTolerance); - Assert.Equal(MassUnit.Stone, stoneQuantity.Unit); - - var tonneQuantity = kilogram.ToUnit(MassUnit.Tonne); - AssertEx.EqualTolerance(TonnesInOneKilogram, (double)tonneQuantity.Value, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, tonneQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Mass kilogram = Mass.FromKilograms(1); - AssertEx.EqualTolerance(1, Mass.FromCentigrams(kilogram.Centigrams).Kilograms, CentigramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromDecagrams(kilogram.Decagrams).Kilograms, DecagramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromDecigrams(kilogram.Decigrams).Kilograms, DecigramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromGrams(kilogram.Grams).Kilograms, GramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromHectograms(kilogram.Hectograms).Kilograms, HectogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilograms(kilogram.Kilograms).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilopounds(kilogram.Kilopounds).Kilograms, KilopoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilotonnes(kilogram.Kilotonnes).Kilograms, KilotonnesTolerance); - AssertEx.EqualTolerance(1, Mass.FromLongHundredweight(kilogram.LongHundredweight).Kilograms, LongHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.FromLongTons(kilogram.LongTons).Kilograms, LongTonsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMegapounds(kilogram.Megapounds).Kilograms, MegapoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMegatonnes(kilogram.Megatonnes).Kilograms, MegatonnesTolerance); - AssertEx.EqualTolerance(1, Mass.FromMicrograms(kilogram.Micrograms).Kilograms, MicrogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMilligrams(kilogram.Milligrams).Kilograms, MilligramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromNanograms(kilogram.Nanograms).Kilograms, NanogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromOunces(kilogram.Ounces).Kilograms, OuncesTolerance); - AssertEx.EqualTolerance(1, Mass.FromPounds(kilogram.Pounds).Kilograms, PoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromShortHundredweight(kilogram.ShortHundredweight).Kilograms, ShortHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.FromShortTons(kilogram.ShortTons).Kilograms, ShortTonsTolerance); - AssertEx.EqualTolerance(1, Mass.FromSlugs(kilogram.Slugs).Kilograms, SlugsTolerance); - AssertEx.EqualTolerance(1, Mass.FromStone(kilogram.Stone).Kilograms, StoneTolerance); - AssertEx.EqualTolerance(1, Mass.FromTonnes(kilogram.Tonnes).Kilograms, TonnesTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Mass v = Mass.FromKilograms(1); - AssertEx.EqualTolerance(-1, -v.Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (Mass.FromKilograms(3)-v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (v + v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(10, (v*10).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(10, (10*v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (Mass.FromKilograms(10)/5).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, Mass.FromKilograms(10)/Mass.FromKilograms(5), KilogramsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Mass oneKilogram = Mass.FromKilograms(1); - Mass twoKilograms = Mass.FromKilograms(2); - - Assert.True(oneKilogram < twoKilograms); - Assert.True(oneKilogram <= twoKilograms); - Assert.True(twoKilograms > oneKilogram); - Assert.True(twoKilograms >= oneKilogram); - - Assert.False(oneKilogram > twoKilograms); - Assert.False(oneKilogram >= twoKilograms); - Assert.False(twoKilograms < oneKilogram); - Assert.False(twoKilograms <= oneKilogram); - } - - [Fact] - public void CompareToIsImplemented() - { - Mass kilogram = Mass.FromKilograms(1); - Assert.Equal(0, kilogram.CompareTo(kilogram)); - Assert.True(kilogram.CompareTo(Mass.Zero) > 0); - Assert.True(Mass.Zero.CompareTo(kilogram) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Mass kilogram = Mass.FromKilograms(1); - Assert.Throws(() => kilogram.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Mass kilogram = Mass.FromKilograms(1); - Assert.Throws(() => kilogram.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Mass a = Mass.FromKilograms(1); - Mass b = Mass.FromKilograms(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Mass v = Mass.FromKilograms(1); - Assert.True(v.Equals(Mass.FromKilograms(1), Mass.FromKilograms(KilogramsTolerance))); - Assert.False(v.Equals(Mass.Zero, Mass.FromKilograms(KilogramsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Mass kilogram = Mass.FromKilograms(1); - Assert.False(kilogram.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Mass kilogram = Mass.FromKilograms(1); - Assert.False(kilogram.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassUnit.Undefined, Mass.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MolarEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MolarEnergyTestsBase.g.cs deleted file mode 100644 index 920f219a95..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MolarEnergyTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MolarEnergy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MolarEnergyTestsBase - { - protected abstract double JoulesPerMoleInOneJoulePerMole { get; } - protected abstract double KilojoulesPerMoleInOneJoulePerMole { get; } - protected abstract double MegajoulesPerMoleInOneJoulePerMole { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerMoleTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerMoleTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerMoleToMolarEnergyUnits() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(JoulesPerMoleInOneJoulePerMole, joulepermole.JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(KilojoulesPerMoleInOneJoulePerMole, joulepermole.KilojoulesPerMole, KilojoulesPerMoleTolerance); - AssertEx.EqualTolerance(MegajoulesPerMoleInOneJoulePerMole, joulepermole.MegajoulesPerMole, MegajoulesPerMoleTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MolarEnergy.From(1, MolarEnergyUnit.JoulePerMole).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.From(1, MolarEnergyUnit.KilojoulePerMole).KilojoulesPerMole, KilojoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.From(1, MolarEnergyUnit.MegajoulePerMole).MegajoulesPerMole, MegajoulesPerMoleTolerance); - } - - [Fact] - public void As() - { - var joulepermole = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(JoulesPerMoleInOneJoulePerMole, joulepermole.As(MolarEnergyUnit.JoulePerMole), JoulesPerMoleTolerance); - AssertEx.EqualTolerance(KilojoulesPerMoleInOneJoulePerMole, joulepermole.As(MolarEnergyUnit.KilojoulePerMole), KilojoulesPerMoleTolerance); - AssertEx.EqualTolerance(MegajoulesPerMoleInOneJoulePerMole, joulepermole.As(MolarEnergyUnit.MegajoulePerMole), MegajoulesPerMoleTolerance); - } - - [Fact] - public void ToUnit() - { - var joulepermole = MolarEnergy.FromJoulesPerMole(1); - - var joulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.JoulePerMole); - AssertEx.EqualTolerance(JoulesPerMoleInOneJoulePerMole, (double)joulepermoleQuantity.Value, JoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.JoulePerMole, joulepermoleQuantity.Unit); - - var kilojoulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.KilojoulePerMole); - AssertEx.EqualTolerance(KilojoulesPerMoleInOneJoulePerMole, (double)kilojoulepermoleQuantity.Value, KilojoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.KilojoulePerMole, kilojoulepermoleQuantity.Unit); - - var megajoulepermoleQuantity = joulepermole.ToUnit(MolarEnergyUnit.MegajoulePerMole); - AssertEx.EqualTolerance(MegajoulesPerMoleInOneJoulePerMole, (double)megajoulepermoleQuantity.Value, MegajoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.MegajoulePerMole, megajoulepermoleQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(1, MolarEnergy.FromJoulesPerMole(joulepermole.JoulesPerMole).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.FromKilojoulesPerMole(joulepermole.KilojoulesPerMole).JoulesPerMole, KilojoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.FromMegajoulesPerMole(joulepermole.MegajoulesPerMole).JoulesPerMole, MegajoulesPerMoleTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MolarEnergy v = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarEnergy.FromJoulesPerMole(3)-v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarEnergy.FromJoulesPerMole(10)/5).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, MolarEnergy.FromJoulesPerMole(10)/MolarEnergy.FromJoulesPerMole(5), JoulesPerMoleTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MolarEnergy oneJoulePerMole = MolarEnergy.FromJoulesPerMole(1); - MolarEnergy twoJoulesPerMole = MolarEnergy.FromJoulesPerMole(2); - - Assert.True(oneJoulePerMole < twoJoulesPerMole); - Assert.True(oneJoulePerMole <= twoJoulesPerMole); - Assert.True(twoJoulesPerMole > oneJoulePerMole); - Assert.True(twoJoulesPerMole >= oneJoulePerMole); - - Assert.False(oneJoulePerMole > twoJoulesPerMole); - Assert.False(oneJoulePerMole >= twoJoulesPerMole); - Assert.False(twoJoulesPerMole < oneJoulePerMole); - Assert.False(twoJoulesPerMole <= oneJoulePerMole); - } - - [Fact] - public void CompareToIsImplemented() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.Equal(0, joulepermole.CompareTo(joulepermole)); - Assert.True(joulepermole.CompareTo(MolarEnergy.Zero) > 0); - Assert.True(MolarEnergy.Zero.CompareTo(joulepermole) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.Throws(() => joulepermole.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.Throws(() => joulepermole.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MolarEnergy a = MolarEnergy.FromJoulesPerMole(1); - MolarEnergy b = MolarEnergy.FromJoulesPerMole(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MolarEnergy v = MolarEnergy.FromJoulesPerMole(1); - Assert.True(v.Equals(MolarEnergy.FromJoulesPerMole(1), MolarEnergy.FromJoulesPerMole(JoulesPerMoleTolerance))); - Assert.False(v.Equals(MolarEnergy.Zero, MolarEnergy.FromJoulesPerMole(JoulesPerMoleTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.False(joulepermole.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.False(joulepermole.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarEnergyUnit.Undefined, MolarEnergy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MolarEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MolarEntropyTestsBase.g.cs deleted file mode 100644 index 7892dcd4e6..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MolarEntropyTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MolarEntropy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MolarEntropyTestsBase - { - protected abstract double JoulesPerMoleKelvinInOneJoulePerMoleKelvin { get; } - protected abstract double KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin { get; } - protected abstract double MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double JoulesPerMoleKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerMoleKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerMoleKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerMoleKelvinToMolarEntropyUnits() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(JoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.KilojoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.MegajoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MolarEntropy.From(1, MolarEntropyUnit.JoulePerMoleKelvin).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.From(1, MolarEntropyUnit.KilojoulePerMoleKelvin).KilojoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.From(1, MolarEntropyUnit.MegajoulePerMoleKelvin).MegajoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); - } - - [Fact] - public void As() - { - var joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(JoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.As(MolarEntropyUnit.JoulePerMoleKelvin), JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.As(MolarEntropyUnit.KilojoulePerMoleKelvin), KilojoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin, joulepermolekelvin.As(MolarEntropyUnit.MegajoulePerMoleKelvin), MegajoulesPerMoleKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - - var joulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin); - AssertEx.EqualTolerance(JoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)joulepermolekelvinQuantity.Value, JoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, joulepermolekelvinQuantity.Unit); - - var kilojoulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.KilojoulePerMoleKelvin); - AssertEx.EqualTolerance(KilojoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)kilojoulepermolekelvinQuantity.Value, KilojoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.KilojoulePerMoleKelvin, kilojoulepermolekelvinQuantity.Unit); - - var megajoulepermolekelvinQuantity = joulepermolekelvin.ToUnit(MolarEntropyUnit.MegajoulePerMoleKelvin); - AssertEx.EqualTolerance(MegajoulesPerMoleKelvinInOneJoulePerMoleKelvin, (double)megajoulepermolekelvinQuantity.Value, MegajoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.MegajoulePerMoleKelvin, megajoulepermolekelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(1, MolarEntropy.FromJoulesPerMoleKelvin(joulepermolekelvin.JoulesPerMoleKelvin).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.FromKilojoulesPerMoleKelvin(joulepermolekelvin.KilojoulesPerMoleKelvin).JoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.FromMegajoulesPerMoleKelvin(joulepermolekelvin.MegajoulesPerMoleKelvin).JoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MolarEntropy v = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (MolarEntropy.FromJoulesPerMoleKelvin(3)-v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (MolarEntropy.FromJoulesPerMoleKelvin(10)/5).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, MolarEntropy.FromJoulesPerMoleKelvin(10)/MolarEntropy.FromJoulesPerMoleKelvin(5), JoulesPerMoleKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MolarEntropy oneJoulePerMoleKelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - MolarEntropy twoJoulesPerMoleKelvin = MolarEntropy.FromJoulesPerMoleKelvin(2); - - Assert.True(oneJoulePerMoleKelvin < twoJoulesPerMoleKelvin); - Assert.True(oneJoulePerMoleKelvin <= twoJoulesPerMoleKelvin); - Assert.True(twoJoulesPerMoleKelvin > oneJoulePerMoleKelvin); - Assert.True(twoJoulesPerMoleKelvin >= oneJoulePerMoleKelvin); - - Assert.False(oneJoulePerMoleKelvin > twoJoulesPerMoleKelvin); - Assert.False(oneJoulePerMoleKelvin >= twoJoulesPerMoleKelvin); - Assert.False(twoJoulesPerMoleKelvin < oneJoulePerMoleKelvin); - Assert.False(twoJoulesPerMoleKelvin <= oneJoulePerMoleKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.Equal(0, joulepermolekelvin.CompareTo(joulepermolekelvin)); - Assert.True(joulepermolekelvin.CompareTo(MolarEntropy.Zero) > 0); - Assert.True(MolarEntropy.Zero.CompareTo(joulepermolekelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.Throws(() => joulepermolekelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.Throws(() => joulepermolekelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MolarEntropy a = MolarEntropy.FromJoulesPerMoleKelvin(1); - MolarEntropy b = MolarEntropy.FromJoulesPerMoleKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MolarEntropy v = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.True(v.Equals(MolarEntropy.FromJoulesPerMoleKelvin(1), MolarEntropy.FromJoulesPerMoleKelvin(JoulesPerMoleKelvinTolerance))); - Assert.False(v.Equals(MolarEntropy.Zero, MolarEntropy.FromJoulesPerMoleKelvin(JoulesPerMoleKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.False(joulepermolekelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.False(joulepermolekelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarEntropyUnit.Undefined, MolarEntropy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MolarMassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MolarMassTestsBase.g.cs deleted file mode 100644 index 83f82c605b..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MolarMassTestsBase.g.cs +++ /dev/null @@ -1,307 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of MolarMass. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MolarMassTestsBase - { - protected abstract double CentigramsPerMoleInOneKilogramPerMole { get; } - protected abstract double DecagramsPerMoleInOneKilogramPerMole { get; } - protected abstract double DecigramsPerMoleInOneKilogramPerMole { get; } - protected abstract double GramsPerMoleInOneKilogramPerMole { get; } - protected abstract double HectogramsPerMoleInOneKilogramPerMole { get; } - protected abstract double KilogramsPerMoleInOneKilogramPerMole { get; } - protected abstract double KilopoundsPerMoleInOneKilogramPerMole { get; } - protected abstract double MegapoundsPerMoleInOneKilogramPerMole { get; } - protected abstract double MicrogramsPerMoleInOneKilogramPerMole { get; } - protected abstract double MilligramsPerMoleInOneKilogramPerMole { get; } - protected abstract double NanogramsPerMoleInOneKilogramPerMole { get; } - protected abstract double PoundsPerMoleInOneKilogramPerMole { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentigramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double DecagramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double DecigramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double GramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double HectogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double KilopoundsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MegapoundsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MicrogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double MilligramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double NanogramsPerMoleTolerance { get { return 1e-5; } } - protected virtual double PoundsPerMoleTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KilogramPerMoleToMolarMassUnits() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(CentigramsPerMoleInOneKilogramPerMole, kilogrampermole.CentigramsPerMole, CentigramsPerMoleTolerance); - AssertEx.EqualTolerance(DecagramsPerMoleInOneKilogramPerMole, kilogrampermole.DecagramsPerMole, DecagramsPerMoleTolerance); - AssertEx.EqualTolerance(DecigramsPerMoleInOneKilogramPerMole, kilogrampermole.DecigramsPerMole, DecigramsPerMoleTolerance); - AssertEx.EqualTolerance(GramsPerMoleInOneKilogramPerMole, kilogrampermole.GramsPerMole, GramsPerMoleTolerance); - AssertEx.EqualTolerance(HectogramsPerMoleInOneKilogramPerMole, kilogrampermole.HectogramsPerMole, HectogramsPerMoleTolerance); - AssertEx.EqualTolerance(KilogramsPerMoleInOneKilogramPerMole, kilogrampermole.KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(KilopoundsPerMoleInOneKilogramPerMole, kilogrampermole.KilopoundsPerMole, KilopoundsPerMoleTolerance); - AssertEx.EqualTolerance(MegapoundsPerMoleInOneKilogramPerMole, kilogrampermole.MegapoundsPerMole, MegapoundsPerMoleTolerance); - AssertEx.EqualTolerance(MicrogramsPerMoleInOneKilogramPerMole, kilogrampermole.MicrogramsPerMole, MicrogramsPerMoleTolerance); - AssertEx.EqualTolerance(MilligramsPerMoleInOneKilogramPerMole, kilogrampermole.MilligramsPerMole, MilligramsPerMoleTolerance); - AssertEx.EqualTolerance(NanogramsPerMoleInOneKilogramPerMole, kilogrampermole.NanogramsPerMole, NanogramsPerMoleTolerance); - AssertEx.EqualTolerance(PoundsPerMoleInOneKilogramPerMole, kilogrampermole.PoundsPerMole, PoundsPerMoleTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.CentigramPerMole).CentigramsPerMole, CentigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.DecagramPerMole).DecagramsPerMole, DecagramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.DecigramPerMole).DecigramsPerMole, DecigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.GramPerMole).GramsPerMole, GramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.HectogramPerMole).HectogramsPerMole, HectogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.KilogramPerMole).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.KilopoundPerMole).KilopoundsPerMole, KilopoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.MegapoundPerMole).MegapoundsPerMole, MegapoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.MicrogramPerMole).MicrogramsPerMole, MicrogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.MilligramPerMole).MilligramsPerMole, MilligramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.NanogramPerMole).NanogramsPerMole, NanogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.From(1, MolarMassUnit.PoundPerMole).PoundsPerMole, PoundsPerMoleTolerance); - } - - [Fact] - public void As() - { - var kilogrampermole = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(CentigramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.CentigramPerMole), CentigramsPerMoleTolerance); - AssertEx.EqualTolerance(DecagramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.DecagramPerMole), DecagramsPerMoleTolerance); - AssertEx.EqualTolerance(DecigramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.DecigramPerMole), DecigramsPerMoleTolerance); - AssertEx.EqualTolerance(GramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.GramPerMole), GramsPerMoleTolerance); - AssertEx.EqualTolerance(HectogramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.HectogramPerMole), HectogramsPerMoleTolerance); - AssertEx.EqualTolerance(KilogramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.KilogramPerMole), KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(KilopoundsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.KilopoundPerMole), KilopoundsPerMoleTolerance); - AssertEx.EqualTolerance(MegapoundsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.MegapoundPerMole), MegapoundsPerMoleTolerance); - AssertEx.EqualTolerance(MicrogramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.MicrogramPerMole), MicrogramsPerMoleTolerance); - AssertEx.EqualTolerance(MilligramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.MilligramPerMole), MilligramsPerMoleTolerance); - AssertEx.EqualTolerance(NanogramsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.NanogramPerMole), NanogramsPerMoleTolerance); - AssertEx.EqualTolerance(PoundsPerMoleInOneKilogramPerMole, kilogrampermole.As(MolarMassUnit.PoundPerMole), PoundsPerMoleTolerance); - } - - [Fact] - public void ToUnit() - { - var kilogrampermole = MolarMass.FromKilogramsPerMole(1); - - var centigrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.CentigramPerMole); - AssertEx.EqualTolerance(CentigramsPerMoleInOneKilogramPerMole, (double)centigrampermoleQuantity.Value, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, centigrampermoleQuantity.Unit); - - var decagrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.DecagramPerMole); - AssertEx.EqualTolerance(DecagramsPerMoleInOneKilogramPerMole, (double)decagrampermoleQuantity.Value, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, decagrampermoleQuantity.Unit); - - var decigrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.DecigramPerMole); - AssertEx.EqualTolerance(DecigramsPerMoleInOneKilogramPerMole, (double)decigrampermoleQuantity.Value, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, decigrampermoleQuantity.Unit); - - var grampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.GramPerMole); - AssertEx.EqualTolerance(GramsPerMoleInOneKilogramPerMole, (double)grampermoleQuantity.Value, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, grampermoleQuantity.Unit); - - var hectogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.HectogramPerMole); - AssertEx.EqualTolerance(HectogramsPerMoleInOneKilogramPerMole, (double)hectogrampermoleQuantity.Value, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, hectogrampermoleQuantity.Unit); - - var kilogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.KilogramPerMole); - AssertEx.EqualTolerance(KilogramsPerMoleInOneKilogramPerMole, (double)kilogrampermoleQuantity.Value, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, kilogrampermoleQuantity.Unit); - - var kilopoundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.KilopoundPerMole); - AssertEx.EqualTolerance(KilopoundsPerMoleInOneKilogramPerMole, (double)kilopoundpermoleQuantity.Value, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, kilopoundpermoleQuantity.Unit); - - var megapoundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MegapoundPerMole); - AssertEx.EqualTolerance(MegapoundsPerMoleInOneKilogramPerMole, (double)megapoundpermoleQuantity.Value, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, megapoundpermoleQuantity.Unit); - - var microgrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MicrogramPerMole); - AssertEx.EqualTolerance(MicrogramsPerMoleInOneKilogramPerMole, (double)microgrampermoleQuantity.Value, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, microgrampermoleQuantity.Unit); - - var milligrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.MilligramPerMole); - AssertEx.EqualTolerance(MilligramsPerMoleInOneKilogramPerMole, (double)milligrampermoleQuantity.Value, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, milligrampermoleQuantity.Unit); - - var nanogrampermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.NanogramPerMole); - AssertEx.EqualTolerance(NanogramsPerMoleInOneKilogramPerMole, (double)nanogrampermoleQuantity.Value, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, nanogrampermoleQuantity.Unit); - - var poundpermoleQuantity = kilogrampermole.ToUnit(MolarMassUnit.PoundPerMole); - AssertEx.EqualTolerance(PoundsPerMoleInOneKilogramPerMole, (double)poundpermoleQuantity.Value, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, poundpermoleQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(1, MolarMass.FromCentigramsPerMole(kilogrampermole.CentigramsPerMole).KilogramsPerMole, CentigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromDecagramsPerMole(kilogrampermole.DecagramsPerMole).KilogramsPerMole, DecagramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromDecigramsPerMole(kilogrampermole.DecigramsPerMole).KilogramsPerMole, DecigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromGramsPerMole(kilogrampermole.GramsPerMole).KilogramsPerMole, GramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromHectogramsPerMole(kilogrampermole.HectogramsPerMole).KilogramsPerMole, HectogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromKilogramsPerMole(kilogrampermole.KilogramsPerMole).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromKilopoundsPerMole(kilogrampermole.KilopoundsPerMole).KilogramsPerMole, KilopoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMegapoundsPerMole(kilogrampermole.MegapoundsPerMole).KilogramsPerMole, MegapoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMicrogramsPerMole(kilogrampermole.MicrogramsPerMole).KilogramsPerMole, MicrogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMilligramsPerMole(kilogrampermole.MilligramsPerMole).KilogramsPerMole, MilligramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromNanogramsPerMole(kilogrampermole.NanogramsPerMole).KilogramsPerMole, NanogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromPoundsPerMole(kilogrampermole.PoundsPerMole).KilogramsPerMole, PoundsPerMoleTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - MolarMass v = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarMass.FromKilogramsPerMole(3)-v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarMass.FromKilogramsPerMole(10)/5).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, MolarMass.FromKilogramsPerMole(10)/MolarMass.FromKilogramsPerMole(5), KilogramsPerMoleTolerance); - } - - [Fact] - public void ComparisonOperators() - { - MolarMass oneKilogramPerMole = MolarMass.FromKilogramsPerMole(1); - MolarMass twoKilogramsPerMole = MolarMass.FromKilogramsPerMole(2); - - Assert.True(oneKilogramPerMole < twoKilogramsPerMole); - Assert.True(oneKilogramPerMole <= twoKilogramsPerMole); - Assert.True(twoKilogramsPerMole > oneKilogramPerMole); - Assert.True(twoKilogramsPerMole >= oneKilogramPerMole); - - Assert.False(oneKilogramPerMole > twoKilogramsPerMole); - Assert.False(oneKilogramPerMole >= twoKilogramsPerMole); - Assert.False(twoKilogramsPerMole < oneKilogramPerMole); - Assert.False(twoKilogramsPerMole <= oneKilogramPerMole); - } - - [Fact] - public void CompareToIsImplemented() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - Assert.Equal(0, kilogrampermole.CompareTo(kilogrampermole)); - Assert.True(kilogrampermole.CompareTo(MolarMass.Zero) > 0); - Assert.True(MolarMass.Zero.CompareTo(kilogrampermole) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - Assert.Throws(() => kilogrampermole.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - Assert.Throws(() => kilogrampermole.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - MolarMass a = MolarMass.FromKilogramsPerMole(1); - MolarMass b = MolarMass.FromKilogramsPerMole(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - MolarMass v = MolarMass.FromKilogramsPerMole(1); - Assert.True(v.Equals(MolarMass.FromKilogramsPerMole(1), MolarMass.FromKilogramsPerMole(KilogramsPerMoleTolerance))); - Assert.False(v.Equals(MolarMass.Zero, MolarMass.FromKilogramsPerMole(KilogramsPerMoleTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - Assert.False(kilogrampermole.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - Assert.False(kilogrampermole.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarMassUnit.Undefined, MolarMass.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/MolarityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/MolarityTestsBase.g.cs deleted file mode 100644 index d918cebc4f..0000000000 --- a/UnitsNet.Tests/GeneratedCode/MolarityTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Molarity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class MolarityTestsBase - { - protected abstract double CentimolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double DecimolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double MicromolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double MillimolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double MolesPerCubicMeterInOneMolesPerCubicMeter { get; } - protected abstract double MolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double NanomolesPerLiterInOneMolesPerCubicMeter { get; } - protected abstract double PicomolesPerLiterInOneMolesPerCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double DecimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicromolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MillimolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double MolesPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanomolesPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicomolesPerLiterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void MolesPerCubicMeterToMolarityUnits() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(CentimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.CentimolesPerLiter, CentimolesPerLiterTolerance); - AssertEx.EqualTolerance(DecimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.DecimolesPerLiter, DecimolesPerLiterTolerance); - AssertEx.EqualTolerance(MicromolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.MicromolesPerLiter, MicromolesPerLiterTolerance); - AssertEx.EqualTolerance(MillimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.MillimolesPerLiter, MillimolesPerLiterTolerance); - AssertEx.EqualTolerance(MolesPerCubicMeterInOneMolesPerCubicMeter, molespercubicmeter.MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(MolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.MolesPerLiter, MolesPerLiterTolerance); - AssertEx.EqualTolerance(NanomolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.NanomolesPerLiter, NanomolesPerLiterTolerance); - AssertEx.EqualTolerance(PicomolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.PicomolesPerLiter, PicomolesPerLiterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.CentimolesPerLiter).CentimolesPerLiter, CentimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.DecimolesPerLiter).DecimolesPerLiter, DecimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.MicromolesPerLiter).MicromolesPerLiter, MicromolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.MillimolesPerLiter).MillimolesPerLiter, MillimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.MolesPerCubicMeter).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.MolesPerLiter).MolesPerLiter, MolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.NanomolesPerLiter).NanomolesPerLiter, NanomolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.From(1, MolarityUnit.PicomolesPerLiter).PicomolesPerLiter, PicomolesPerLiterTolerance); - } - - [Fact] - public void As() - { - var molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(CentimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.CentimolesPerLiter), CentimolesPerLiterTolerance); - AssertEx.EqualTolerance(DecimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.DecimolesPerLiter), DecimolesPerLiterTolerance); - AssertEx.EqualTolerance(MicromolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.MicromolesPerLiter), MicromolesPerLiterTolerance); - AssertEx.EqualTolerance(MillimolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.MillimolesPerLiter), MillimolesPerLiterTolerance); - AssertEx.EqualTolerance(MolesPerCubicMeterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.MolesPerCubicMeter), MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(MolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.MolesPerLiter), MolesPerLiterTolerance); - AssertEx.EqualTolerance(NanomolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.NanomolesPerLiter), NanomolesPerLiterTolerance); - AssertEx.EqualTolerance(PicomolesPerLiterInOneMolesPerCubicMeter, molespercubicmeter.As(MolarityUnit.PicomolesPerLiter), PicomolesPerLiterTolerance); - } - - [Fact] - public void ToUnit() - { - var molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - - var centimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.CentimolesPerLiter); - AssertEx.EqualTolerance(CentimolesPerLiterInOneMolesPerCubicMeter, (double)centimolesperliterQuantity.Value, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolesPerLiter, centimolesperliterQuantity.Unit); - - var decimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.DecimolesPerLiter); - AssertEx.EqualTolerance(DecimolesPerLiterInOneMolesPerCubicMeter, (double)decimolesperliterQuantity.Value, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolesPerLiter, decimolesperliterQuantity.Unit); - - var micromolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MicromolesPerLiter); - AssertEx.EqualTolerance(MicromolesPerLiterInOneMolesPerCubicMeter, (double)micromolesperliterQuantity.Value, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolesPerLiter, micromolesperliterQuantity.Unit); - - var millimolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MillimolesPerLiter); - AssertEx.EqualTolerance(MillimolesPerLiterInOneMolesPerCubicMeter, (double)millimolesperliterQuantity.Value, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolesPerLiter, millimolesperliterQuantity.Unit); - - var molespercubicmeterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MolesPerCubicMeter); - AssertEx.EqualTolerance(MolesPerCubicMeterInOneMolesPerCubicMeter, (double)molespercubicmeterQuantity.Value, MolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.MolesPerCubicMeter, molespercubicmeterQuantity.Unit); - - var molesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.MolesPerLiter); - AssertEx.EqualTolerance(MolesPerLiterInOneMolesPerCubicMeter, (double)molesperliterQuantity.Value, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolesPerLiter, molesperliterQuantity.Unit); - - var nanomolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.NanomolesPerLiter); - AssertEx.EqualTolerance(NanomolesPerLiterInOneMolesPerCubicMeter, (double)nanomolesperliterQuantity.Value, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolesPerLiter, nanomolesperliterQuantity.Unit); - - var picomolesperliterQuantity = molespercubicmeter.ToUnit(MolarityUnit.PicomolesPerLiter); - AssertEx.EqualTolerance(PicomolesPerLiterInOneMolesPerCubicMeter, (double)picomolesperliterQuantity.Value, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolesPerLiter, picomolesperliterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(1, Molarity.FromCentimolesPerLiter(molespercubicmeter.CentimolesPerLiter).MolesPerCubicMeter, CentimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromDecimolesPerLiter(molespercubicmeter.DecimolesPerLiter).MolesPerCubicMeter, DecimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMicromolesPerLiter(molespercubicmeter.MicromolesPerLiter).MolesPerCubicMeter, MicromolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMillimolesPerLiter(molespercubicmeter.MillimolesPerLiter).MolesPerCubicMeter, MillimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMolesPerCubicMeter(molespercubicmeter.MolesPerCubicMeter).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMolesPerLiter(molespercubicmeter.MolesPerLiter).MolesPerCubicMeter, MolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromNanomolesPerLiter(molespercubicmeter.NanomolesPerLiter).MolesPerCubicMeter, NanomolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromPicomolesPerLiter(molespercubicmeter.PicomolesPerLiter).MolesPerCubicMeter, PicomolesPerLiterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Molarity v = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Molarity.FromMolesPerCubicMeter(3)-v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Molarity.FromMolesPerCubicMeter(10)/5).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, Molarity.FromMolesPerCubicMeter(10)/Molarity.FromMolesPerCubicMeter(5), MolesPerCubicMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Molarity oneMolesPerCubicMeter = Molarity.FromMolesPerCubicMeter(1); - Molarity twoMolesPerCubicMeter = Molarity.FromMolesPerCubicMeter(2); - - Assert.True(oneMolesPerCubicMeter < twoMolesPerCubicMeter); - Assert.True(oneMolesPerCubicMeter <= twoMolesPerCubicMeter); - Assert.True(twoMolesPerCubicMeter > oneMolesPerCubicMeter); - Assert.True(twoMolesPerCubicMeter >= oneMolesPerCubicMeter); - - Assert.False(oneMolesPerCubicMeter > twoMolesPerCubicMeter); - Assert.False(oneMolesPerCubicMeter >= twoMolesPerCubicMeter); - Assert.False(twoMolesPerCubicMeter < oneMolesPerCubicMeter); - Assert.False(twoMolesPerCubicMeter <= oneMolesPerCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - Assert.Equal(0, molespercubicmeter.CompareTo(molespercubicmeter)); - Assert.True(molespercubicmeter.CompareTo(Molarity.Zero) > 0); - Assert.True(Molarity.Zero.CompareTo(molespercubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - Assert.Throws(() => molespercubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - Assert.Throws(() => molespercubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Molarity a = Molarity.FromMolesPerCubicMeter(1); - Molarity b = Molarity.FromMolesPerCubicMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Molarity v = Molarity.FromMolesPerCubicMeter(1); - Assert.True(v.Equals(Molarity.FromMolesPerCubicMeter(1), Molarity.FromMolesPerCubicMeter(MolesPerCubicMeterTolerance))); - Assert.False(v.Equals(Molarity.Zero, Molarity.FromMolesPerCubicMeter(MolesPerCubicMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - Assert.False(molespercubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Molarity molespercubicmeter = Molarity.FromMolesPerCubicMeter(1); - Assert.False(molespercubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarityUnit.Undefined, Molarity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PermeabilityTestsBase.g.cs deleted file mode 100644 index 0826bfbfdd..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PermeabilityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Permeability. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PermeabilityTestsBase - { - protected abstract double HenriesPerMeterInOneHenryPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HenriesPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void HenryPerMeterToPermeabilityUnits() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(HenriesPerMeterInOneHenryPerMeter, henrypermeter.HenriesPerMeter, HenriesPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Permeability.From(1, PermeabilityUnit.HenryPerMeter).HenriesPerMeter, HenriesPerMeterTolerance); - } - - [Fact] - public void As() - { - var henrypermeter = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(HenriesPerMeterInOneHenryPerMeter, henrypermeter.As(PermeabilityUnit.HenryPerMeter), HenriesPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var henrypermeter = Permeability.FromHenriesPerMeter(1); - - var henrypermeterQuantity = henrypermeter.ToUnit(PermeabilityUnit.HenryPerMeter); - AssertEx.EqualTolerance(HenriesPerMeterInOneHenryPerMeter, (double)henrypermeterQuantity.Value, HenriesPerMeterTolerance); - Assert.Equal(PermeabilityUnit.HenryPerMeter, henrypermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(1, Permeability.FromHenriesPerMeter(henrypermeter.HenriesPerMeter).HenriesPerMeter, HenriesPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Permeability v = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(-1, -v.HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permeability.FromHenriesPerMeter(3)-v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permeability.FromHenriesPerMeter(10)/5).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, Permeability.FromHenriesPerMeter(10)/Permeability.FromHenriesPerMeter(5), HenriesPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Permeability oneHenryPerMeter = Permeability.FromHenriesPerMeter(1); - Permeability twoHenriesPerMeter = Permeability.FromHenriesPerMeter(2); - - Assert.True(oneHenryPerMeter < twoHenriesPerMeter); - Assert.True(oneHenryPerMeter <= twoHenriesPerMeter); - Assert.True(twoHenriesPerMeter > oneHenryPerMeter); - Assert.True(twoHenriesPerMeter >= oneHenryPerMeter); - - Assert.False(oneHenryPerMeter > twoHenriesPerMeter); - Assert.False(oneHenryPerMeter >= twoHenriesPerMeter); - Assert.False(twoHenriesPerMeter < oneHenryPerMeter); - Assert.False(twoHenriesPerMeter <= oneHenryPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.Equal(0, henrypermeter.CompareTo(henrypermeter)); - Assert.True(henrypermeter.CompareTo(Permeability.Zero) > 0); - Assert.True(Permeability.Zero.CompareTo(henrypermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.Throws(() => henrypermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.Throws(() => henrypermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Permeability a = Permeability.FromHenriesPerMeter(1); - Permeability b = Permeability.FromHenriesPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Permeability v = Permeability.FromHenriesPerMeter(1); - Assert.True(v.Equals(Permeability.FromHenriesPerMeter(1), Permeability.FromHenriesPerMeter(HenriesPerMeterTolerance))); - Assert.False(v.Equals(Permeability.Zero, Permeability.FromHenriesPerMeter(HenriesPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.False(henrypermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.False(henrypermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PermeabilityUnit.Undefined, Permeability.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PermittivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PermittivityTestsBase.g.cs deleted file mode 100644 index f3137f003a..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PermittivityTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Permittivity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PermittivityTestsBase - { - protected abstract double FaradsPerMeterInOneFaradPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double FaradsPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void FaradPerMeterToPermittivityUnits() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(FaradsPerMeterInOneFaradPerMeter, faradpermeter.FaradsPerMeter, FaradsPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Permittivity.From(1, PermittivityUnit.FaradPerMeter).FaradsPerMeter, FaradsPerMeterTolerance); - } - - [Fact] - public void As() - { - var faradpermeter = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(FaradsPerMeterInOneFaradPerMeter, faradpermeter.As(PermittivityUnit.FaradPerMeter), FaradsPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var faradpermeter = Permittivity.FromFaradsPerMeter(1); - - var faradpermeterQuantity = faradpermeter.ToUnit(PermittivityUnit.FaradPerMeter); - AssertEx.EqualTolerance(FaradsPerMeterInOneFaradPerMeter, (double)faradpermeterQuantity.Value, FaradsPerMeterTolerance); - Assert.Equal(PermittivityUnit.FaradPerMeter, faradpermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(1, Permittivity.FromFaradsPerMeter(faradpermeter.FaradsPerMeter).FaradsPerMeter, FaradsPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Permittivity v = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permittivity.FromFaradsPerMeter(3)-v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permittivity.FromFaradsPerMeter(10)/5).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, Permittivity.FromFaradsPerMeter(10)/Permittivity.FromFaradsPerMeter(5), FaradsPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Permittivity oneFaradPerMeter = Permittivity.FromFaradsPerMeter(1); - Permittivity twoFaradsPerMeter = Permittivity.FromFaradsPerMeter(2); - - Assert.True(oneFaradPerMeter < twoFaradsPerMeter); - Assert.True(oneFaradPerMeter <= twoFaradsPerMeter); - Assert.True(twoFaradsPerMeter > oneFaradPerMeter); - Assert.True(twoFaradsPerMeter >= oneFaradPerMeter); - - Assert.False(oneFaradPerMeter > twoFaradsPerMeter); - Assert.False(oneFaradPerMeter >= twoFaradsPerMeter); - Assert.False(twoFaradsPerMeter < oneFaradPerMeter); - Assert.False(twoFaradsPerMeter <= oneFaradPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.Equal(0, faradpermeter.CompareTo(faradpermeter)); - Assert.True(faradpermeter.CompareTo(Permittivity.Zero) > 0); - Assert.True(Permittivity.Zero.CompareTo(faradpermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.Throws(() => faradpermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.Throws(() => faradpermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Permittivity a = Permittivity.FromFaradsPerMeter(1); - Permittivity b = Permittivity.FromFaradsPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Permittivity v = Permittivity.FromFaradsPerMeter(1); - Assert.True(v.Equals(Permittivity.FromFaradsPerMeter(1), Permittivity.FromFaradsPerMeter(FaradsPerMeterTolerance))); - Assert.False(v.Equals(Permittivity.Zero, Permittivity.FromFaradsPerMeter(FaradsPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.False(faradpermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.False(faradpermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PermittivityUnit.Undefined, Permittivity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PowerDensityTestsBase.g.cs deleted file mode 100644 index 7ec8597875..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PowerDensityTestsBase.g.cs +++ /dev/null @@ -1,627 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of PowerDensity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PowerDensityTestsBase - { - protected abstract double DecawattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double DecawattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double DecawattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double DecawattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double DeciwattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double DeciwattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double DeciwattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double DeciwattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double GigawattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double GigawattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double GigawattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double GigawattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double KilowattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double KilowattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double KilowattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double KilowattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double MegawattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double MegawattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double MegawattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double MegawattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double MicrowattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double MicrowattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double MicrowattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double MicrowattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double MilliwattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double MilliwattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double MilliwattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double MilliwattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double NanowattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double NanowattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double NanowattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double NanowattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double PicowattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double PicowattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double PicowattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double PicowattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double TerawattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double TerawattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double TerawattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double TerawattsPerLiterInOneWattPerCubicMeter { get; } - protected abstract double WattsPerCubicFootInOneWattPerCubicMeter { get; } - protected abstract double WattsPerCubicInchInOneWattPerCubicMeter { get; } - protected abstract double WattsPerCubicMeterInOneWattPerCubicMeter { get; } - protected abstract double WattsPerLiterInOneWattPerCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double DecawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double DeciwattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double GigawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MegawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MicrowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double MilliwattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NanowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double PicowattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TerawattsPerLiterTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicFootTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicInchTolerance { get { return 1e-5; } } - protected virtual double WattsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double WattsPerLiterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattPerCubicMeterToPowerDensityUnits() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(DecawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.DecawattsPerCubicFoot, DecawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(DecawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.DecawattsPerCubicInch, DecawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(DecawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.DecawattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(DecawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.DecawattsPerLiter, DecawattsPerLiterTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.DeciwattsPerCubicFoot, DeciwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.DeciwattsPerCubicInch, DeciwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.DeciwattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(DeciwattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.DeciwattsPerLiter, DeciwattsPerLiterTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.GigawattsPerCubicFoot, GigawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.GigawattsPerCubicInch, GigawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.GigawattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(GigawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.GigawattsPerLiter, GigawattsPerLiterTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.KilowattsPerCubicFoot, KilowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.KilowattsPerCubicInch, KilowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.KilowattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.KilowattsPerLiter, KilowattsPerLiterTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.MegawattsPerCubicFoot, MegawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.MegawattsPerCubicInch, MegawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.MegawattsPerCubicMeter, MegawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MegawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.MegawattsPerLiter, MegawattsPerLiterTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.MicrowattsPerCubicFoot, MicrowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.MicrowattsPerCubicInch, MicrowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.MicrowattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MicrowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.MicrowattsPerLiter, MicrowattsPerLiterTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.MilliwattsPerCubicFoot, MilliwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.MilliwattsPerCubicInch, MilliwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.MilliwattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MilliwattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.MilliwattsPerLiter, MilliwattsPerLiterTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.NanowattsPerCubicFoot, NanowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.NanowattsPerCubicInch, NanowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.NanowattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NanowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.NanowattsPerLiter, NanowattsPerLiterTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.PicowattsPerCubicFoot, PicowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.PicowattsPerCubicInch, PicowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.PicowattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(PicowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.PicowattsPerLiter, PicowattsPerLiterTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.TerawattsPerCubicFoot, TerawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.TerawattsPerCubicInch, TerawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.TerawattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(TerawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.TerawattsPerLiter, TerawattsPerLiterTolerance); - AssertEx.EqualTolerance(WattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.WattsPerCubicFoot, WattsPerCubicFootTolerance); - AssertEx.EqualTolerance(WattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.WattsPerCubicInch, WattsPerCubicInchTolerance); - AssertEx.EqualTolerance(WattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(WattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.WattsPerLiter, WattsPerLiterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicFoot).DecawattsPerCubicFoot, DecawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicInch).DecawattsPerCubicInch, DecawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicMeter).DecawattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DecawattPerLiter).DecawattsPerLiter, DecawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicFoot).DeciwattsPerCubicFoot, DeciwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicInch).DeciwattsPerCubicInch, DeciwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicMeter).DeciwattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.DeciwattPerLiter).DeciwattsPerLiter, DeciwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicFoot).GigawattsPerCubicFoot, GigawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicInch).GigawattsPerCubicInch, GigawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicMeter).GigawattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.GigawattPerLiter).GigawattsPerLiter, GigawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicFoot).KilowattsPerCubicFoot, KilowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicInch).KilowattsPerCubicInch, KilowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicMeter).KilowattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.KilowattPerLiter).KilowattsPerLiter, KilowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicFoot).MegawattsPerCubicFoot, MegawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicInch).MegawattsPerCubicInch, MegawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicMeter).MegawattsPerCubicMeter, MegawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MegawattPerLiter).MegawattsPerLiter, MegawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicFoot).MicrowattsPerCubicFoot, MicrowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicInch).MicrowattsPerCubicInch, MicrowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicMeter).MicrowattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MicrowattPerLiter).MicrowattsPerLiter, MicrowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicFoot).MilliwattsPerCubicFoot, MilliwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicInch).MilliwattsPerCubicInch, MilliwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicMeter).MilliwattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.MilliwattPerLiter).MilliwattsPerLiter, MilliwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicFoot).NanowattsPerCubicFoot, NanowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicInch).NanowattsPerCubicInch, NanowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicMeter).NanowattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.NanowattPerLiter).NanowattsPerLiter, NanowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicFoot).PicowattsPerCubicFoot, PicowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicInch).PicowattsPerCubicInch, PicowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicMeter).PicowattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.PicowattPerLiter).PicowattsPerLiter, PicowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicFoot).TerawattsPerCubicFoot, TerawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicInch).TerawattsPerCubicInch, TerawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicMeter).TerawattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.TerawattPerLiter).TerawattsPerLiter, TerawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.WattPerCubicFoot).WattsPerCubicFoot, WattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.WattPerCubicInch).WattsPerCubicInch, WattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.WattPerCubicMeter).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.From(1, PowerDensityUnit.WattPerLiter).WattsPerLiter, WattsPerLiterTolerance); - } - - [Fact] - public void As() - { - var wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(DecawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DecawattPerCubicFoot), DecawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(DecawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DecawattPerCubicInch), DecawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(DecawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DecawattPerCubicMeter), DecawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(DecawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DecawattPerLiter), DecawattsPerLiterTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DeciwattPerCubicFoot), DeciwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DeciwattPerCubicInch), DeciwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(DeciwattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DeciwattPerCubicMeter), DeciwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(DeciwattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.DeciwattPerLiter), DeciwattsPerLiterTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.GigawattPerCubicFoot), GigawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.GigawattPerCubicInch), GigawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(GigawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.GigawattPerCubicMeter), GigawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(GigawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.GigawattPerLiter), GigawattsPerLiterTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.KilowattPerCubicFoot), KilowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.KilowattPerCubicInch), KilowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(KilowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.KilowattPerCubicMeter), KilowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.KilowattPerLiter), KilowattsPerLiterTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MegawattPerCubicFoot), MegawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MegawattPerCubicInch), MegawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MegawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MegawattPerCubicMeter), MegawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MegawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MegawattPerLiter), MegawattsPerLiterTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MicrowattPerCubicFoot), MicrowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MicrowattPerCubicInch), MicrowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MicrowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MicrowattPerCubicMeter), MicrowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MicrowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MicrowattPerLiter), MicrowattsPerLiterTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MilliwattPerCubicFoot), MilliwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MilliwattPerCubicInch), MilliwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(MilliwattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MilliwattPerCubicMeter), MilliwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(MilliwattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.MilliwattPerLiter), MilliwattsPerLiterTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.NanowattPerCubicFoot), NanowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.NanowattPerCubicInch), NanowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(NanowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.NanowattPerCubicMeter), NanowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NanowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.NanowattPerLiter), NanowattsPerLiterTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.PicowattPerCubicFoot), PicowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.PicowattPerCubicInch), PicowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(PicowattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.PicowattPerCubicMeter), PicowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(PicowattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.PicowattPerLiter), PicowattsPerLiterTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.TerawattPerCubicFoot), TerawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.TerawattPerCubicInch), TerawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(TerawattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.TerawattPerCubicMeter), TerawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(TerawattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.TerawattPerLiter), TerawattsPerLiterTolerance); - AssertEx.EqualTolerance(WattsPerCubicFootInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.WattPerCubicFoot), WattsPerCubicFootTolerance); - AssertEx.EqualTolerance(WattsPerCubicInchInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.WattPerCubicInch), WattsPerCubicInchTolerance); - AssertEx.EqualTolerance(WattsPerCubicMeterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.WattPerCubicMeter), WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(WattsPerLiterInOneWattPerCubicMeter, wattpercubicmeter.As(PowerDensityUnit.WattPerLiter), WattsPerLiterTolerance); - } - - [Fact] - public void ToUnit() - { - var wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - - var decawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicFoot); - AssertEx.EqualTolerance(DecawattsPerCubicFootInOneWattPerCubicMeter, (double)decawattpercubicfootQuantity.Value, DecawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicFoot, decawattpercubicfootQuantity.Unit); - - var decawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicInch); - AssertEx.EqualTolerance(DecawattsPerCubicInchInOneWattPerCubicMeter, (double)decawattpercubicinchQuantity.Value, DecawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicInch, decawattpercubicinchQuantity.Unit); - - var decawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerCubicMeter); - AssertEx.EqualTolerance(DecawattsPerCubicMeterInOneWattPerCubicMeter, (double)decawattpercubicmeterQuantity.Value, DecawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicMeter, decawattpercubicmeterQuantity.Unit); - - var decawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DecawattPerLiter); - AssertEx.EqualTolerance(DecawattsPerLiterInOneWattPerCubicMeter, (double)decawattperliterQuantity.Value, DecawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerLiter, decawattperliterQuantity.Unit); - - var deciwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicFoot); - AssertEx.EqualTolerance(DeciwattsPerCubicFootInOneWattPerCubicMeter, (double)deciwattpercubicfootQuantity.Value, DeciwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicFoot, deciwattpercubicfootQuantity.Unit); - - var deciwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicInch); - AssertEx.EqualTolerance(DeciwattsPerCubicInchInOneWattPerCubicMeter, (double)deciwattpercubicinchQuantity.Value, DeciwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicInch, deciwattpercubicinchQuantity.Unit); - - var deciwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerCubicMeter); - AssertEx.EqualTolerance(DeciwattsPerCubicMeterInOneWattPerCubicMeter, (double)deciwattpercubicmeterQuantity.Value, DeciwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicMeter, deciwattpercubicmeterQuantity.Unit); - - var deciwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.DeciwattPerLiter); - AssertEx.EqualTolerance(DeciwattsPerLiterInOneWattPerCubicMeter, (double)deciwattperliterQuantity.Value, DeciwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerLiter, deciwattperliterQuantity.Unit); - - var gigawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicFoot); - AssertEx.EqualTolerance(GigawattsPerCubicFootInOneWattPerCubicMeter, (double)gigawattpercubicfootQuantity.Value, GigawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicFoot, gigawattpercubicfootQuantity.Unit); - - var gigawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicInch); - AssertEx.EqualTolerance(GigawattsPerCubicInchInOneWattPerCubicMeter, (double)gigawattpercubicinchQuantity.Value, GigawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicInch, gigawattpercubicinchQuantity.Unit); - - var gigawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerCubicMeter); - AssertEx.EqualTolerance(GigawattsPerCubicMeterInOneWattPerCubicMeter, (double)gigawattpercubicmeterQuantity.Value, GigawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicMeter, gigawattpercubicmeterQuantity.Unit); - - var gigawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.GigawattPerLiter); - AssertEx.EqualTolerance(GigawattsPerLiterInOneWattPerCubicMeter, (double)gigawattperliterQuantity.Value, GigawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerLiter, gigawattperliterQuantity.Unit); - - var kilowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicFoot); - AssertEx.EqualTolerance(KilowattsPerCubicFootInOneWattPerCubicMeter, (double)kilowattpercubicfootQuantity.Value, KilowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicFoot, kilowattpercubicfootQuantity.Unit); - - var kilowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicInch); - AssertEx.EqualTolerance(KilowattsPerCubicInchInOneWattPerCubicMeter, (double)kilowattpercubicinchQuantity.Value, KilowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicInch, kilowattpercubicinchQuantity.Unit); - - var kilowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerCubicMeter); - AssertEx.EqualTolerance(KilowattsPerCubicMeterInOneWattPerCubicMeter, (double)kilowattpercubicmeterQuantity.Value, KilowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicMeter, kilowattpercubicmeterQuantity.Unit); - - var kilowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.KilowattPerLiter); - AssertEx.EqualTolerance(KilowattsPerLiterInOneWattPerCubicMeter, (double)kilowattperliterQuantity.Value, KilowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerLiter, kilowattperliterQuantity.Unit); - - var megawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicFoot); - AssertEx.EqualTolerance(MegawattsPerCubicFootInOneWattPerCubicMeter, (double)megawattpercubicfootQuantity.Value, MegawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicFoot, megawattpercubicfootQuantity.Unit); - - var megawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicInch); - AssertEx.EqualTolerance(MegawattsPerCubicInchInOneWattPerCubicMeter, (double)megawattpercubicinchQuantity.Value, MegawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicInch, megawattpercubicinchQuantity.Unit); - - var megawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerCubicMeter); - AssertEx.EqualTolerance(MegawattsPerCubicMeterInOneWattPerCubicMeter, (double)megawattpercubicmeterQuantity.Value, MegawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicMeter, megawattpercubicmeterQuantity.Unit); - - var megawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MegawattPerLiter); - AssertEx.EqualTolerance(MegawattsPerLiterInOneWattPerCubicMeter, (double)megawattperliterQuantity.Value, MegawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerLiter, megawattperliterQuantity.Unit); - - var microwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicFoot); - AssertEx.EqualTolerance(MicrowattsPerCubicFootInOneWattPerCubicMeter, (double)microwattpercubicfootQuantity.Value, MicrowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicFoot, microwattpercubicfootQuantity.Unit); - - var microwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicInch); - AssertEx.EqualTolerance(MicrowattsPerCubicInchInOneWattPerCubicMeter, (double)microwattpercubicinchQuantity.Value, MicrowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicInch, microwattpercubicinchQuantity.Unit); - - var microwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerCubicMeter); - AssertEx.EqualTolerance(MicrowattsPerCubicMeterInOneWattPerCubicMeter, (double)microwattpercubicmeterQuantity.Value, MicrowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicMeter, microwattpercubicmeterQuantity.Unit); - - var microwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MicrowattPerLiter); - AssertEx.EqualTolerance(MicrowattsPerLiterInOneWattPerCubicMeter, (double)microwattperliterQuantity.Value, MicrowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerLiter, microwattperliterQuantity.Unit); - - var milliwattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicFoot); - AssertEx.EqualTolerance(MilliwattsPerCubicFootInOneWattPerCubicMeter, (double)milliwattpercubicfootQuantity.Value, MilliwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicFoot, milliwattpercubicfootQuantity.Unit); - - var milliwattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicInch); - AssertEx.EqualTolerance(MilliwattsPerCubicInchInOneWattPerCubicMeter, (double)milliwattpercubicinchQuantity.Value, MilliwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicInch, milliwattpercubicinchQuantity.Unit); - - var milliwattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerCubicMeter); - AssertEx.EqualTolerance(MilliwattsPerCubicMeterInOneWattPerCubicMeter, (double)milliwattpercubicmeterQuantity.Value, MilliwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicMeter, milliwattpercubicmeterQuantity.Unit); - - var milliwattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.MilliwattPerLiter); - AssertEx.EqualTolerance(MilliwattsPerLiterInOneWattPerCubicMeter, (double)milliwattperliterQuantity.Value, MilliwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerLiter, milliwattperliterQuantity.Unit); - - var nanowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicFoot); - AssertEx.EqualTolerance(NanowattsPerCubicFootInOneWattPerCubicMeter, (double)nanowattpercubicfootQuantity.Value, NanowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicFoot, nanowattpercubicfootQuantity.Unit); - - var nanowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicInch); - AssertEx.EqualTolerance(NanowattsPerCubicInchInOneWattPerCubicMeter, (double)nanowattpercubicinchQuantity.Value, NanowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicInch, nanowattpercubicinchQuantity.Unit); - - var nanowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerCubicMeter); - AssertEx.EqualTolerance(NanowattsPerCubicMeterInOneWattPerCubicMeter, (double)nanowattpercubicmeterQuantity.Value, NanowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicMeter, nanowattpercubicmeterQuantity.Unit); - - var nanowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.NanowattPerLiter); - AssertEx.EqualTolerance(NanowattsPerLiterInOneWattPerCubicMeter, (double)nanowattperliterQuantity.Value, NanowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerLiter, nanowattperliterQuantity.Unit); - - var picowattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicFoot); - AssertEx.EqualTolerance(PicowattsPerCubicFootInOneWattPerCubicMeter, (double)picowattpercubicfootQuantity.Value, PicowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicFoot, picowattpercubicfootQuantity.Unit); - - var picowattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicInch); - AssertEx.EqualTolerance(PicowattsPerCubicInchInOneWattPerCubicMeter, (double)picowattpercubicinchQuantity.Value, PicowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicInch, picowattpercubicinchQuantity.Unit); - - var picowattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerCubicMeter); - AssertEx.EqualTolerance(PicowattsPerCubicMeterInOneWattPerCubicMeter, (double)picowattpercubicmeterQuantity.Value, PicowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicMeter, picowattpercubicmeterQuantity.Unit); - - var picowattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.PicowattPerLiter); - AssertEx.EqualTolerance(PicowattsPerLiterInOneWattPerCubicMeter, (double)picowattperliterQuantity.Value, PicowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerLiter, picowattperliterQuantity.Unit); - - var terawattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicFoot); - AssertEx.EqualTolerance(TerawattsPerCubicFootInOneWattPerCubicMeter, (double)terawattpercubicfootQuantity.Value, TerawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicFoot, terawattpercubicfootQuantity.Unit); - - var terawattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicInch); - AssertEx.EqualTolerance(TerawattsPerCubicInchInOneWattPerCubicMeter, (double)terawattpercubicinchQuantity.Value, TerawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicInch, terawattpercubicinchQuantity.Unit); - - var terawattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerCubicMeter); - AssertEx.EqualTolerance(TerawattsPerCubicMeterInOneWattPerCubicMeter, (double)terawattpercubicmeterQuantity.Value, TerawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicMeter, terawattpercubicmeterQuantity.Unit); - - var terawattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.TerawattPerLiter); - AssertEx.EqualTolerance(TerawattsPerLiterInOneWattPerCubicMeter, (double)terawattperliterQuantity.Value, TerawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerLiter, terawattperliterQuantity.Unit); - - var wattpercubicfootQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicFoot); - AssertEx.EqualTolerance(WattsPerCubicFootInOneWattPerCubicMeter, (double)wattpercubicfootQuantity.Value, WattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicFoot, wattpercubicfootQuantity.Unit); - - var wattpercubicinchQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicInch); - AssertEx.EqualTolerance(WattsPerCubicInchInOneWattPerCubicMeter, (double)wattpercubicinchQuantity.Value, WattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicInch, wattpercubicinchQuantity.Unit); - - var wattpercubicmeterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerCubicMeter); - AssertEx.EqualTolerance(WattsPerCubicMeterInOneWattPerCubicMeter, (double)wattpercubicmeterQuantity.Value, WattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicMeter, wattpercubicmeterQuantity.Unit); - - var wattperliterQuantity = wattpercubicmeter.ToUnit(PowerDensityUnit.WattPerLiter); - AssertEx.EqualTolerance(WattsPerLiterInOneWattPerCubicMeter, (double)wattperliterQuantity.Value, WattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.WattPerLiter, wattperliterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicFoot(wattpercubicmeter.DecawattsPerCubicFoot).WattsPerCubicMeter, DecawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicInch(wattpercubicmeter.DecawattsPerCubicInch).WattsPerCubicMeter, DecawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicMeter(wattpercubicmeter.DecawattsPerCubicMeter).WattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerLiter(wattpercubicmeter.DecawattsPerLiter).WattsPerCubicMeter, DecawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicFoot(wattpercubicmeter.DeciwattsPerCubicFoot).WattsPerCubicMeter, DeciwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicInch(wattpercubicmeter.DeciwattsPerCubicInch).WattsPerCubicMeter, DeciwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicMeter(wattpercubicmeter.DeciwattsPerCubicMeter).WattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerLiter(wattpercubicmeter.DeciwattsPerLiter).WattsPerCubicMeter, DeciwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicFoot(wattpercubicmeter.GigawattsPerCubicFoot).WattsPerCubicMeter, GigawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicInch(wattpercubicmeter.GigawattsPerCubicInch).WattsPerCubicMeter, GigawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicMeter(wattpercubicmeter.GigawattsPerCubicMeter).WattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerLiter(wattpercubicmeter.GigawattsPerLiter).WattsPerCubicMeter, GigawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicFoot(wattpercubicmeter.KilowattsPerCubicFoot).WattsPerCubicMeter, KilowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicInch(wattpercubicmeter.KilowattsPerCubicInch).WattsPerCubicMeter, KilowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicMeter(wattpercubicmeter.KilowattsPerCubicMeter).WattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerLiter(wattpercubicmeter.KilowattsPerLiter).WattsPerCubicMeter, KilowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicFoot(wattpercubicmeter.MegawattsPerCubicFoot).WattsPerCubicMeter, MegawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicInch(wattpercubicmeter.MegawattsPerCubicInch).WattsPerCubicMeter, MegawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicMeter(wattpercubicmeter.MegawattsPerCubicMeter).WattsPerCubicMeter, MegawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerLiter(wattpercubicmeter.MegawattsPerLiter).WattsPerCubicMeter, MegawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicFoot(wattpercubicmeter.MicrowattsPerCubicFoot).WattsPerCubicMeter, MicrowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicInch(wattpercubicmeter.MicrowattsPerCubicInch).WattsPerCubicMeter, MicrowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicMeter(wattpercubicmeter.MicrowattsPerCubicMeter).WattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerLiter(wattpercubicmeter.MicrowattsPerLiter).WattsPerCubicMeter, MicrowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicFoot(wattpercubicmeter.MilliwattsPerCubicFoot).WattsPerCubicMeter, MilliwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicInch(wattpercubicmeter.MilliwattsPerCubicInch).WattsPerCubicMeter, MilliwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicMeter(wattpercubicmeter.MilliwattsPerCubicMeter).WattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerLiter(wattpercubicmeter.MilliwattsPerLiter).WattsPerCubicMeter, MilliwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicFoot(wattpercubicmeter.NanowattsPerCubicFoot).WattsPerCubicMeter, NanowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicInch(wattpercubicmeter.NanowattsPerCubicInch).WattsPerCubicMeter, NanowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicMeter(wattpercubicmeter.NanowattsPerCubicMeter).WattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerLiter(wattpercubicmeter.NanowattsPerLiter).WattsPerCubicMeter, NanowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicFoot(wattpercubicmeter.PicowattsPerCubicFoot).WattsPerCubicMeter, PicowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicInch(wattpercubicmeter.PicowattsPerCubicInch).WattsPerCubicMeter, PicowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicMeter(wattpercubicmeter.PicowattsPerCubicMeter).WattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerLiter(wattpercubicmeter.PicowattsPerLiter).WattsPerCubicMeter, PicowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicFoot(wattpercubicmeter.TerawattsPerCubicFoot).WattsPerCubicMeter, TerawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicInch(wattpercubicmeter.TerawattsPerCubicInch).WattsPerCubicMeter, TerawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicMeter(wattpercubicmeter.TerawattsPerCubicMeter).WattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerLiter(wattpercubicmeter.TerawattsPerLiter).WattsPerCubicMeter, TerawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicFoot(wattpercubicmeter.WattsPerCubicFoot).WattsPerCubicMeter, WattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicInch(wattpercubicmeter.WattsPerCubicInch).WattsPerCubicMeter, WattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicMeter(wattpercubicmeter.WattsPerCubicMeter).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerLiter(wattpercubicmeter.WattsPerLiter).WattsPerCubicMeter, WattsPerLiterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - PowerDensity v = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (PowerDensity.FromWattsPerCubicMeter(3)-v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (PowerDensity.FromWattsPerCubicMeter(10)/5).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, PowerDensity.FromWattsPerCubicMeter(10)/PowerDensity.FromWattsPerCubicMeter(5), WattsPerCubicMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - PowerDensity oneWattPerCubicMeter = PowerDensity.FromWattsPerCubicMeter(1); - PowerDensity twoWattsPerCubicMeter = PowerDensity.FromWattsPerCubicMeter(2); - - Assert.True(oneWattPerCubicMeter < twoWattsPerCubicMeter); - Assert.True(oneWattPerCubicMeter <= twoWattsPerCubicMeter); - Assert.True(twoWattsPerCubicMeter > oneWattPerCubicMeter); - Assert.True(twoWattsPerCubicMeter >= oneWattPerCubicMeter); - - Assert.False(oneWattPerCubicMeter > twoWattsPerCubicMeter); - Assert.False(oneWattPerCubicMeter >= twoWattsPerCubicMeter); - Assert.False(twoWattsPerCubicMeter < oneWattPerCubicMeter); - Assert.False(twoWattsPerCubicMeter <= oneWattPerCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - Assert.Equal(0, wattpercubicmeter.CompareTo(wattpercubicmeter)); - Assert.True(wattpercubicmeter.CompareTo(PowerDensity.Zero) > 0); - Assert.True(PowerDensity.Zero.CompareTo(wattpercubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - Assert.Throws(() => wattpercubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - Assert.Throws(() => wattpercubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - PowerDensity a = PowerDensity.FromWattsPerCubicMeter(1); - PowerDensity b = PowerDensity.FromWattsPerCubicMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - PowerDensity v = PowerDensity.FromWattsPerCubicMeter(1); - Assert.True(v.Equals(PowerDensity.FromWattsPerCubicMeter(1), PowerDensity.FromWattsPerCubicMeter(WattsPerCubicMeterTolerance))); - Assert.False(v.Equals(PowerDensity.Zero, PowerDensity.FromWattsPerCubicMeter(WattsPerCubicMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - Assert.False(wattpercubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - Assert.False(wattpercubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerDensityUnit.Undefined, PowerDensity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PowerRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PowerRatioTestsBase.g.cs deleted file mode 100644 index 9ee129a240..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PowerRatioTestsBase.g.cs +++ /dev/null @@ -1,212 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of PowerRatio. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PowerRatioTestsBase - { - protected abstract double DecibelMilliwattsInOneDecibelWatt { get; } - protected abstract double DecibelWattsInOneDecibelWatt { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecibelMilliwattsTolerance { get { return 1e-5; } } - protected virtual double DecibelWattsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DecibelWattToPowerRatioUnits() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - AssertEx.EqualTolerance(DecibelMilliwattsInOneDecibelWatt, decibelwatt.DecibelMilliwatts, DecibelMilliwattsTolerance); - AssertEx.EqualTolerance(DecibelWattsInOneDecibelWatt, decibelwatt.DecibelWatts, DecibelWattsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, PowerRatio.From(1, PowerRatioUnit.DecibelMilliwatt).DecibelMilliwatts, DecibelMilliwattsTolerance); - AssertEx.EqualTolerance(1, PowerRatio.From(1, PowerRatioUnit.DecibelWatt).DecibelWatts, DecibelWattsTolerance); - } - - [Fact] - public void As() - { - var decibelwatt = PowerRatio.FromDecibelWatts(1); - AssertEx.EqualTolerance(DecibelMilliwattsInOneDecibelWatt, decibelwatt.As(PowerRatioUnit.DecibelMilliwatt), DecibelMilliwattsTolerance); - AssertEx.EqualTolerance(DecibelWattsInOneDecibelWatt, decibelwatt.As(PowerRatioUnit.DecibelWatt), DecibelWattsTolerance); - } - - [Fact] - public void ToUnit() - { - var decibelwatt = PowerRatio.FromDecibelWatts(1); - - var decibelmilliwattQuantity = decibelwatt.ToUnit(PowerRatioUnit.DecibelMilliwatt); - AssertEx.EqualTolerance(DecibelMilliwattsInOneDecibelWatt, (double)decibelmilliwattQuantity.Value, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, decibelmilliwattQuantity.Unit); - - var decibelwattQuantity = decibelwatt.ToUnit(PowerRatioUnit.DecibelWatt); - AssertEx.EqualTolerance(DecibelWattsInOneDecibelWatt, (double)decibelwattQuantity.Value, DecibelWattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelWatt, decibelwattQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - AssertEx.EqualTolerance(1, PowerRatio.FromDecibelMilliwatts(decibelwatt.DecibelMilliwatts).DecibelWatts, DecibelMilliwattsTolerance); - AssertEx.EqualTolerance(1, PowerRatio.FromDecibelWatts(decibelwatt.DecibelWatts).DecibelWatts, DecibelWattsTolerance); - } - - [Fact] - public void LogarithmicArithmeticOperators() - { - PowerRatio v = PowerRatio.FromDecibelWatts(40); - AssertEx.EqualTolerance(-40, -v.DecibelWatts, DecibelWattsTolerance); - AssertLogarithmicAddition(); - AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(50, (10*v).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(35, (v/5).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(35, v/PowerRatio.FromDecibelWatts(5), DecibelWattsTolerance); - } - - protected abstract void AssertLogarithmicAddition(); - - protected abstract void AssertLogarithmicSubtraction(); - - - [Fact] - public void ComparisonOperators() - { - PowerRatio oneDecibelWatt = PowerRatio.FromDecibelWatts(1); - PowerRatio twoDecibelWatts = PowerRatio.FromDecibelWatts(2); - - Assert.True(oneDecibelWatt < twoDecibelWatts); - Assert.True(oneDecibelWatt <= twoDecibelWatts); - Assert.True(twoDecibelWatts > oneDecibelWatt); - Assert.True(twoDecibelWatts >= oneDecibelWatt); - - Assert.False(oneDecibelWatt > twoDecibelWatts); - Assert.False(oneDecibelWatt >= twoDecibelWatts); - Assert.False(twoDecibelWatts < oneDecibelWatt); - Assert.False(twoDecibelWatts <= oneDecibelWatt); - } - - [Fact] - public void CompareToIsImplemented() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.Equal(0, decibelwatt.CompareTo(decibelwatt)); - Assert.True(decibelwatt.CompareTo(PowerRatio.Zero) > 0); - Assert.True(PowerRatio.Zero.CompareTo(decibelwatt) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.Throws(() => decibelwatt.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.Throws(() => decibelwatt.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - PowerRatio a = PowerRatio.FromDecibelWatts(1); - PowerRatio b = PowerRatio.FromDecibelWatts(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - PowerRatio v = PowerRatio.FromDecibelWatts(1); - Assert.True(v.Equals(PowerRatio.FromDecibelWatts(1), PowerRatio.FromDecibelWatts(DecibelWattsTolerance))); - Assert.False(v.Equals(PowerRatio.Zero, PowerRatio.FromDecibelWatts(DecibelWattsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.False(decibelwatt.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.False(decibelwatt.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerRatioUnit.Undefined, PowerRatio.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PowerTestsBase.g.cs deleted file mode 100644 index 894accc13a..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PowerTestsBase.g.cs +++ /dev/null @@ -1,387 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Power. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PowerTestsBase - { - 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 GigawattsInOneWatt { get; } - protected abstract double HydraulicHorsepowerInOneWatt { get; } - protected abstract double KilobritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double KilowattsInOneWatt { get; } - protected abstract double MechanicalHorsepowerInOneWatt { get; } - protected abstract double MegawattsInOneWatt { get; } - protected abstract double MetricHorsepowerInOneWatt { get; } - protected abstract double MicrowattsInOneWatt { 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; } - -// 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 GigawattsTolerance { get { return 1e-5; } } - protected virtual double HydraulicHorsepowerTolerance { get { return 1e-5; } } - protected virtual double KilobritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double KilowattsTolerance { get { return 1e-5; } } - protected virtual double MechanicalHorsepowerTolerance { 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 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; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattToPowerUnits() - { - Power watt = Power.FromWatts(1); - AssertEx.EqualTolerance(BoilerHorsepowerInOneWatt, watt.BoilerHorsepower, BoilerHorsepowerTolerance); - AssertEx.EqualTolerance(BritishThermalUnitsPerHourInOneWatt, watt.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(DecawattsInOneWatt, watt.Decawatts, DecawattsTolerance); - AssertEx.EqualTolerance(DeciwattsInOneWatt, watt.Deciwatts, DeciwattsTolerance); - AssertEx.EqualTolerance(ElectricalHorsepowerInOneWatt, watt.ElectricalHorsepower, ElectricalHorsepowerTolerance); - AssertEx.EqualTolerance(FemtowattsInOneWatt, watt.Femtowatts, FemtowattsTolerance); - AssertEx.EqualTolerance(GigawattsInOneWatt, watt.Gigawatts, GigawattsTolerance); - AssertEx.EqualTolerance(HydraulicHorsepowerInOneWatt, watt.HydraulicHorsepower, HydraulicHorsepowerTolerance); - AssertEx.EqualTolerance(KilobritishThermalUnitsPerHourInOneWatt, watt.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(KilowattsInOneWatt, watt.Kilowatts, KilowattsTolerance); - AssertEx.EqualTolerance(MechanicalHorsepowerInOneWatt, watt.MechanicalHorsepower, MechanicalHorsepowerTolerance); - AssertEx.EqualTolerance(MegawattsInOneWatt, watt.Megawatts, MegawattsTolerance); - AssertEx.EqualTolerance(MetricHorsepowerInOneWatt, watt.MetricHorsepower, MetricHorsepowerTolerance); - AssertEx.EqualTolerance(MicrowattsInOneWatt, watt.Microwatts, MicrowattsTolerance); - AssertEx.EqualTolerance(MilliwattsInOneWatt, watt.Milliwatts, MilliwattsTolerance); - AssertEx.EqualTolerance(NanowattsInOneWatt, watt.Nanowatts, NanowattsTolerance); - AssertEx.EqualTolerance(PetawattsInOneWatt, watt.Petawatts, PetawattsTolerance); - AssertEx.EqualTolerance(PicowattsInOneWatt, watt.Picowatts, PicowattsTolerance); - AssertEx.EqualTolerance(TerawattsInOneWatt, watt.Terawatts, TerawattsTolerance); - AssertEx.EqualTolerance(WattsInOneWatt, watt.Watts, WattsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.BoilerHorsepower).BoilerHorsepower, BoilerHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.BritishThermalUnitPerHour).BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Decawatt).Decawatts, DecawattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Deciwatt).Deciwatts, DeciwattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.ElectricalHorsepower).ElectricalHorsepower, ElectricalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Femtowatt).Femtowatts, FemtowattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Gigawatt).Gigawatts, GigawattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.HydraulicHorsepower).HydraulicHorsepower, HydraulicHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.KilobritishThermalUnitPerHour).KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Kilowatt).Kilowatts, KilowattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.MechanicalHorsepower).MechanicalHorsepower, MechanicalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Megawatt).Megawatts, MegawattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.MetricHorsepower).MetricHorsepower, MetricHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Microwatt).Microwatts, MicrowattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Milliwatt).Milliwatts, MilliwattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Nanowatt).Nanowatts, NanowattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Petawatt).Petawatts, PetawattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Picowatt).Picowatts, PicowattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Terawatt).Terawatts, TerawattsTolerance); - AssertEx.EqualTolerance(1, Power.From(1, PowerUnit.Watt).Watts, WattsTolerance); - } - - [Fact] - public void As() - { - var watt = Power.FromWatts(1); - AssertEx.EqualTolerance(BoilerHorsepowerInOneWatt, watt.As(PowerUnit.BoilerHorsepower), BoilerHorsepowerTolerance); - AssertEx.EqualTolerance(BritishThermalUnitsPerHourInOneWatt, watt.As(PowerUnit.BritishThermalUnitPerHour), BritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(DecawattsInOneWatt, watt.As(PowerUnit.Decawatt), DecawattsTolerance); - AssertEx.EqualTolerance(DeciwattsInOneWatt, watt.As(PowerUnit.Deciwatt), DeciwattsTolerance); - AssertEx.EqualTolerance(ElectricalHorsepowerInOneWatt, watt.As(PowerUnit.ElectricalHorsepower), ElectricalHorsepowerTolerance); - AssertEx.EqualTolerance(FemtowattsInOneWatt, watt.As(PowerUnit.Femtowatt), FemtowattsTolerance); - AssertEx.EqualTolerance(GigawattsInOneWatt, watt.As(PowerUnit.Gigawatt), GigawattsTolerance); - AssertEx.EqualTolerance(HydraulicHorsepowerInOneWatt, watt.As(PowerUnit.HydraulicHorsepower), HydraulicHorsepowerTolerance); - AssertEx.EqualTolerance(KilobritishThermalUnitsPerHourInOneWatt, watt.As(PowerUnit.KilobritishThermalUnitPerHour), KilobritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(KilowattsInOneWatt, watt.As(PowerUnit.Kilowatt), KilowattsTolerance); - AssertEx.EqualTolerance(MechanicalHorsepowerInOneWatt, watt.As(PowerUnit.MechanicalHorsepower), MechanicalHorsepowerTolerance); - AssertEx.EqualTolerance(MegawattsInOneWatt, watt.As(PowerUnit.Megawatt), MegawattsTolerance); - AssertEx.EqualTolerance(MetricHorsepowerInOneWatt, watt.As(PowerUnit.MetricHorsepower), MetricHorsepowerTolerance); - AssertEx.EqualTolerance(MicrowattsInOneWatt, watt.As(PowerUnit.Microwatt), MicrowattsTolerance); - AssertEx.EqualTolerance(MilliwattsInOneWatt, watt.As(PowerUnit.Milliwatt), MilliwattsTolerance); - AssertEx.EqualTolerance(NanowattsInOneWatt, watt.As(PowerUnit.Nanowatt), NanowattsTolerance); - AssertEx.EqualTolerance(PetawattsInOneWatt, watt.As(PowerUnit.Petawatt), PetawattsTolerance); - AssertEx.EqualTolerance(PicowattsInOneWatt, watt.As(PowerUnit.Picowatt), PicowattsTolerance); - AssertEx.EqualTolerance(TerawattsInOneWatt, watt.As(PowerUnit.Terawatt), TerawattsTolerance); - AssertEx.EqualTolerance(WattsInOneWatt, watt.As(PowerUnit.Watt), WattsTolerance); - } - - [Fact] - public void ToUnit() - { - var watt = Power.FromWatts(1); - - var boilerhorsepowerQuantity = watt.ToUnit(PowerUnit.BoilerHorsepower); - AssertEx.EqualTolerance(BoilerHorsepowerInOneWatt, (double)boilerhorsepowerQuantity.Value, BoilerHorsepowerTolerance); - Assert.Equal(PowerUnit.BoilerHorsepower, boilerhorsepowerQuantity.Unit); - - var britishthermalunitperhourQuantity = watt.ToUnit(PowerUnit.BritishThermalUnitPerHour); - AssertEx.EqualTolerance(BritishThermalUnitsPerHourInOneWatt, (double)britishthermalunitperhourQuantity.Value, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, britishthermalunitperhourQuantity.Unit); - - var decawattQuantity = watt.ToUnit(PowerUnit.Decawatt); - AssertEx.EqualTolerance(DecawattsInOneWatt, (double)decawattQuantity.Value, DecawattsTolerance); - Assert.Equal(PowerUnit.Decawatt, decawattQuantity.Unit); - - var deciwattQuantity = watt.ToUnit(PowerUnit.Deciwatt); - AssertEx.EqualTolerance(DeciwattsInOneWatt, (double)deciwattQuantity.Value, DeciwattsTolerance); - Assert.Equal(PowerUnit.Deciwatt, deciwattQuantity.Unit); - - var electricalhorsepowerQuantity = watt.ToUnit(PowerUnit.ElectricalHorsepower); - AssertEx.EqualTolerance(ElectricalHorsepowerInOneWatt, (double)electricalhorsepowerQuantity.Value, ElectricalHorsepowerTolerance); - Assert.Equal(PowerUnit.ElectricalHorsepower, electricalhorsepowerQuantity.Unit); - - var femtowattQuantity = watt.ToUnit(PowerUnit.Femtowatt); - AssertEx.EqualTolerance(FemtowattsInOneWatt, (double)femtowattQuantity.Value, FemtowattsTolerance); - Assert.Equal(PowerUnit.Femtowatt, femtowattQuantity.Unit); - - var gigawattQuantity = watt.ToUnit(PowerUnit.Gigawatt); - AssertEx.EqualTolerance(GigawattsInOneWatt, (double)gigawattQuantity.Value, GigawattsTolerance); - Assert.Equal(PowerUnit.Gigawatt, gigawattQuantity.Unit); - - var hydraulichorsepowerQuantity = watt.ToUnit(PowerUnit.HydraulicHorsepower); - AssertEx.EqualTolerance(HydraulicHorsepowerInOneWatt, (double)hydraulichorsepowerQuantity.Value, HydraulicHorsepowerTolerance); - Assert.Equal(PowerUnit.HydraulicHorsepower, hydraulichorsepowerQuantity.Unit); - - var kilobritishthermalunitperhourQuantity = watt.ToUnit(PowerUnit.KilobritishThermalUnitPerHour); - AssertEx.EqualTolerance(KilobritishThermalUnitsPerHourInOneWatt, (double)kilobritishthermalunitperhourQuantity.Value, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, kilobritishthermalunitperhourQuantity.Unit); - - var kilowattQuantity = watt.ToUnit(PowerUnit.Kilowatt); - AssertEx.EqualTolerance(KilowattsInOneWatt, (double)kilowattQuantity.Value, KilowattsTolerance); - Assert.Equal(PowerUnit.Kilowatt, kilowattQuantity.Unit); - - var mechanicalhorsepowerQuantity = watt.ToUnit(PowerUnit.MechanicalHorsepower); - AssertEx.EqualTolerance(MechanicalHorsepowerInOneWatt, (double)mechanicalhorsepowerQuantity.Value, MechanicalHorsepowerTolerance); - Assert.Equal(PowerUnit.MechanicalHorsepower, mechanicalhorsepowerQuantity.Unit); - - var megawattQuantity = watt.ToUnit(PowerUnit.Megawatt); - AssertEx.EqualTolerance(MegawattsInOneWatt, (double)megawattQuantity.Value, MegawattsTolerance); - Assert.Equal(PowerUnit.Megawatt, megawattQuantity.Unit); - - var metrichorsepowerQuantity = watt.ToUnit(PowerUnit.MetricHorsepower); - AssertEx.EqualTolerance(MetricHorsepowerInOneWatt, (double)metrichorsepowerQuantity.Value, MetricHorsepowerTolerance); - Assert.Equal(PowerUnit.MetricHorsepower, metrichorsepowerQuantity.Unit); - - var microwattQuantity = watt.ToUnit(PowerUnit.Microwatt); - AssertEx.EqualTolerance(MicrowattsInOneWatt, (double)microwattQuantity.Value, MicrowattsTolerance); - Assert.Equal(PowerUnit.Microwatt, microwattQuantity.Unit); - - var milliwattQuantity = watt.ToUnit(PowerUnit.Milliwatt); - AssertEx.EqualTolerance(MilliwattsInOneWatt, (double)milliwattQuantity.Value, MilliwattsTolerance); - Assert.Equal(PowerUnit.Milliwatt, milliwattQuantity.Unit); - - var nanowattQuantity = watt.ToUnit(PowerUnit.Nanowatt); - AssertEx.EqualTolerance(NanowattsInOneWatt, (double)nanowattQuantity.Value, NanowattsTolerance); - Assert.Equal(PowerUnit.Nanowatt, nanowattQuantity.Unit); - - var petawattQuantity = watt.ToUnit(PowerUnit.Petawatt); - AssertEx.EqualTolerance(PetawattsInOneWatt, (double)petawattQuantity.Value, PetawattsTolerance); - Assert.Equal(PowerUnit.Petawatt, petawattQuantity.Unit); - - var picowattQuantity = watt.ToUnit(PowerUnit.Picowatt); - AssertEx.EqualTolerance(PicowattsInOneWatt, (double)picowattQuantity.Value, PicowattsTolerance); - Assert.Equal(PowerUnit.Picowatt, picowattQuantity.Unit); - - var terawattQuantity = watt.ToUnit(PowerUnit.Terawatt); - AssertEx.EqualTolerance(TerawattsInOneWatt, (double)terawattQuantity.Value, TerawattsTolerance); - Assert.Equal(PowerUnit.Terawatt, terawattQuantity.Unit); - - var wattQuantity = watt.ToUnit(PowerUnit.Watt); - AssertEx.EqualTolerance(WattsInOneWatt, (double)wattQuantity.Value, WattsTolerance); - Assert.Equal(PowerUnit.Watt, wattQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Power watt = Power.FromWatts(1); - AssertEx.EqualTolerance(1, Power.FromBoilerHorsepower(watt.BoilerHorsepower).Watts, BoilerHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromBritishThermalUnitsPerHour(watt.BritishThermalUnitsPerHour).Watts, BritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromDecawatts(watt.Decawatts).Watts, DecawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromDeciwatts(watt.Deciwatts).Watts, DeciwattsTolerance); - AssertEx.EqualTolerance(1, Power.FromElectricalHorsepower(watt.ElectricalHorsepower).Watts, ElectricalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromFemtowatts(watt.Femtowatts).Watts, FemtowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromGigawatts(watt.Gigawatts).Watts, GigawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromHydraulicHorsepower(watt.HydraulicHorsepower).Watts, HydraulicHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromKilobritishThermalUnitsPerHour(watt.KilobritishThermalUnitsPerHour).Watts, KilobritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromKilowatts(watt.Kilowatts).Watts, KilowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMechanicalHorsepower(watt.MechanicalHorsepower).Watts, MechanicalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromMegawatts(watt.Megawatts).Watts, MegawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMetricHorsepower(watt.MetricHorsepower).Watts, MetricHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromMicrowatts(watt.Microwatts).Watts, MicrowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMilliwatts(watt.Milliwatts).Watts, MilliwattsTolerance); - AssertEx.EqualTolerance(1, Power.FromNanowatts(watt.Nanowatts).Watts, NanowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromPetawatts(watt.Petawatts).Watts, PetawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromPicowatts(watt.Picowatts).Watts, PicowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromTerawatts(watt.Terawatts).Watts, TerawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromWatts(watt.Watts).Watts, WattsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Power v = Power.FromWatts(1); - AssertEx.EqualTolerance(-1, -v.Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Power.FromWatts(3)-v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (v + v).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (v*10).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (10*v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Power.FromWatts(10)/5).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, Power.FromWatts(10)/Power.FromWatts(5), WattsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Power oneWatt = Power.FromWatts(1); - Power twoWatts = Power.FromWatts(2); - - Assert.True(oneWatt < twoWatts); - Assert.True(oneWatt <= twoWatts); - Assert.True(twoWatts > oneWatt); - Assert.True(twoWatts >= oneWatt); - - Assert.False(oneWatt > twoWatts); - Assert.False(oneWatt >= twoWatts); - Assert.False(twoWatts < oneWatt); - Assert.False(twoWatts <= oneWatt); - } - - [Fact] - public void CompareToIsImplemented() - { - Power watt = Power.FromWatts(1); - Assert.Equal(0, watt.CompareTo(watt)); - Assert.True(watt.CompareTo(Power.Zero) > 0); - Assert.True(Power.Zero.CompareTo(watt) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Power watt = Power.FromWatts(1); - Assert.Throws(() => watt.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Power watt = Power.FromWatts(1); - Assert.Throws(() => watt.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Power a = Power.FromWatts(1); - Power b = Power.FromWatts(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Power v = Power.FromWatts(1); - Assert.True(v.Equals(Power.FromWatts(1), Power.FromWatts(WattsTolerance))); - Assert.False(v.Equals(Power.Zero, Power.FromWatts(WattsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Power watt = Power.FromWatts(1); - Assert.False(watt.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Power watt = Power.FromWatts(1); - Assert.False(watt.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerUnit.Undefined, Power.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PressureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureChangeRateTestsBase.g.cs deleted file mode 100644 index a682b11362..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PressureChangeRateTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of PressureChangeRate. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PressureChangeRateTestsBase - { - protected abstract double AtmospheresPerSecondInOnePascalPerSecond { get; } - protected abstract double KilopascalsPerSecondInOnePascalPerSecond { get; } - protected abstract double MegapascalsPerSecondInOnePascalPerSecond { get; } - protected abstract double PascalsPerSecondInOnePascalPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AtmospheresPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilopascalsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegapascalsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PascalsPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void PascalPerSecondToPressureChangeRateUnits() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(AtmospheresPerSecondInOnePascalPerSecond, pascalpersecond.AtmospheresPerSecond, AtmospheresPerSecondTolerance); - AssertEx.EqualTolerance(KilopascalsPerSecondInOnePascalPerSecond, pascalpersecond.KilopascalsPerSecond, KilopascalsPerSecondTolerance); - AssertEx.EqualTolerance(MegapascalsPerSecondInOnePascalPerSecond, pascalpersecond.MegapascalsPerSecond, MegapascalsPerSecondTolerance); - AssertEx.EqualTolerance(PascalsPerSecondInOnePascalPerSecond, pascalpersecond.PascalsPerSecond, PascalsPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, PressureChangeRate.From(1, PressureChangeRateUnit.AtmospherePerSecond).AtmospheresPerSecond, AtmospheresPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.From(1, PressureChangeRateUnit.KilopascalPerSecond).KilopascalsPerSecond, KilopascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.From(1, PressureChangeRateUnit.MegapascalPerSecond).MegapascalsPerSecond, MegapascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.From(1, PressureChangeRateUnit.PascalPerSecond).PascalsPerSecond, PascalsPerSecondTolerance); - } - - [Fact] - public void As() - { - var pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(AtmospheresPerSecondInOnePascalPerSecond, pascalpersecond.As(PressureChangeRateUnit.AtmospherePerSecond), AtmospheresPerSecondTolerance); - AssertEx.EqualTolerance(KilopascalsPerSecondInOnePascalPerSecond, pascalpersecond.As(PressureChangeRateUnit.KilopascalPerSecond), KilopascalsPerSecondTolerance); - AssertEx.EqualTolerance(MegapascalsPerSecondInOnePascalPerSecond, pascalpersecond.As(PressureChangeRateUnit.MegapascalPerSecond), MegapascalsPerSecondTolerance); - AssertEx.EqualTolerance(PascalsPerSecondInOnePascalPerSecond, pascalpersecond.As(PressureChangeRateUnit.PascalPerSecond), PascalsPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - - var atmospherepersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.AtmospherePerSecond); - AssertEx.EqualTolerance(AtmospheresPerSecondInOnePascalPerSecond, (double)atmospherepersecondQuantity.Value, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, atmospherepersecondQuantity.Unit); - - var kilopascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.KilopascalPerSecond); - AssertEx.EqualTolerance(KilopascalsPerSecondInOnePascalPerSecond, (double)kilopascalpersecondQuantity.Value, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, kilopascalpersecondQuantity.Unit); - - var megapascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.MegapascalPerSecond); - AssertEx.EqualTolerance(MegapascalsPerSecondInOnePascalPerSecond, (double)megapascalpersecondQuantity.Value, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, megapascalpersecondQuantity.Unit); - - var pascalpersecondQuantity = pascalpersecond.ToUnit(PressureChangeRateUnit.PascalPerSecond); - AssertEx.EqualTolerance(PascalsPerSecondInOnePascalPerSecond, (double)pascalpersecondQuantity.Value, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, pascalpersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(1, PressureChangeRate.FromAtmospheresPerSecond(pascalpersecond.AtmospheresPerSecond).PascalsPerSecond, AtmospheresPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromKilopascalsPerSecond(pascalpersecond.KilopascalsPerSecond).PascalsPerSecond, KilopascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMegapascalsPerSecond(pascalpersecond.MegapascalsPerSecond).PascalsPerSecond, MegapascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromPascalsPerSecond(pascalpersecond.PascalsPerSecond).PascalsPerSecond, PascalsPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - PressureChangeRate v = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (PressureChangeRate.FromPascalsPerSecond(3)-v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (PressureChangeRate.FromPascalsPerSecond(10)/5).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, PressureChangeRate.FromPascalsPerSecond(10)/PressureChangeRate.FromPascalsPerSecond(5), PascalsPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - PressureChangeRate onePascalPerSecond = PressureChangeRate.FromPascalsPerSecond(1); - PressureChangeRate twoPascalsPerSecond = PressureChangeRate.FromPascalsPerSecond(2); - - Assert.True(onePascalPerSecond < twoPascalsPerSecond); - Assert.True(onePascalPerSecond <= twoPascalsPerSecond); - Assert.True(twoPascalsPerSecond > onePascalPerSecond); - Assert.True(twoPascalsPerSecond >= onePascalPerSecond); - - Assert.False(onePascalPerSecond > twoPascalsPerSecond); - Assert.False(onePascalPerSecond >= twoPascalsPerSecond); - Assert.False(twoPascalsPerSecond < onePascalPerSecond); - Assert.False(twoPascalsPerSecond <= onePascalPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - Assert.Equal(0, pascalpersecond.CompareTo(pascalpersecond)); - Assert.True(pascalpersecond.CompareTo(PressureChangeRate.Zero) > 0); - Assert.True(PressureChangeRate.Zero.CompareTo(pascalpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - Assert.Throws(() => pascalpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - Assert.Throws(() => pascalpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - PressureChangeRate a = PressureChangeRate.FromPascalsPerSecond(1); - PressureChangeRate b = PressureChangeRate.FromPascalsPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - PressureChangeRate v = PressureChangeRate.FromPascalsPerSecond(1); - Assert.True(v.Equals(PressureChangeRate.FromPascalsPerSecond(1), PressureChangeRate.FromPascalsPerSecond(PascalsPerSecondTolerance))); - Assert.False(v.Equals(PressureChangeRate.Zero, PressureChangeRate.FromPascalsPerSecond(PascalsPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - Assert.False(pascalpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - Assert.False(pascalpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureChangeRateUnit.Undefined, PressureChangeRate.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs deleted file mode 100644 index 79d5e7016e..0000000000 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ /dev/null @@ -1,607 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Pressure. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class PressureTestsBase - { - protected abstract double AtmospheresInOnePascal { get; } - protected abstract double BarsInOnePascal { get; } - protected abstract double CentibarsInOnePascal { get; } - protected abstract double DecapascalsInOnePascal { get; } - protected abstract double DecibarsInOnePascal { get; } - protected abstract double DynesPerSquareCentimeterInOnePascal { get; } - protected abstract double FeetOfHeadInOnePascal { get; } - protected abstract double GigapascalsInOnePascal { get; } - protected abstract double HectopascalsInOnePascal { get; } - protected abstract double InchesOfMercuryInOnePascal { get; } - protected abstract double KilobarsInOnePascal { get; } - protected abstract double KilogramsForcePerSquareCentimeterInOnePascal { get; } - protected abstract double KilogramsForcePerSquareMeterInOnePascal { get; } - protected abstract double KilogramsForcePerSquareMillimeterInOnePascal { get; } - protected abstract double KilonewtonsPerSquareCentimeterInOnePascal { get; } - protected abstract double KilonewtonsPerSquareMeterInOnePascal { get; } - protected abstract double KilonewtonsPerSquareMillimeterInOnePascal { get; } - protected abstract double KilopascalsInOnePascal { get; } - protected abstract double KilopoundsForcePerSquareFootInOnePascal { get; } - protected abstract double KilopoundsForcePerSquareInchInOnePascal { get; } - protected abstract double MegabarsInOnePascal { get; } - protected abstract double MeganewtonsPerSquareMeterInOnePascal { get; } - protected abstract double MegapascalsInOnePascal { get; } - protected abstract double MetersOfHeadInOnePascal { get; } - protected abstract double MicrobarsInOnePascal { get; } - protected abstract double MicropascalsInOnePascal { get; } - protected abstract double MillibarsInOnePascal { get; } - protected abstract double MillimetersOfMercuryInOnePascal { get; } - protected abstract double MillipascalsInOnePascal { get; } - protected abstract double NewtonsPerSquareCentimeterInOnePascal { get; } - protected abstract double NewtonsPerSquareMeterInOnePascal { get; } - protected abstract double NewtonsPerSquareMillimeterInOnePascal { get; } - protected abstract double PascalsInOnePascal { get; } - protected abstract double PoundsForcePerSquareFootInOnePascal { get; } - protected abstract double PoundsForcePerSquareInchInOnePascal { get; } - protected abstract double PoundsPerInchSecondSquaredInOnePascal { get; } - protected abstract double PsiInOnePascal { get; } - protected abstract double TechnicalAtmospheresInOnePascal { get; } - protected abstract double TonnesForcePerSquareCentimeterInOnePascal { get; } - protected abstract double TonnesForcePerSquareMeterInOnePascal { get; } - protected abstract double TonnesForcePerSquareMillimeterInOnePascal { get; } - protected abstract double TorrsInOnePascal { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AtmospheresTolerance { get { return 1e-5; } } - protected virtual double BarsTolerance { get { return 1e-5; } } - protected virtual double CentibarsTolerance { get { return 1e-5; } } - protected virtual double DecapascalsTolerance { get { return 1e-5; } } - protected virtual double DecibarsTolerance { get { return 1e-5; } } - protected virtual double DynesPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double FeetOfHeadTolerance { get { return 1e-5; } } - protected virtual double GigapascalsTolerance { get { return 1e-5; } } - protected virtual double HectopascalsTolerance { get { return 1e-5; } } - protected virtual double InchesOfMercuryTolerance { get { return 1e-5; } } - protected virtual double KilobarsTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopascalsTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerSquareInchTolerance { get { return 1e-5; } } - protected virtual double MegabarsTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double MegapascalsTolerance { get { return 1e-5; } } - protected virtual double MetersOfHeadTolerance { get { return 1e-5; } } - protected virtual double MicrobarsTolerance { get { return 1e-5; } } - protected virtual double MicropascalsTolerance { get { return 1e-5; } } - protected virtual double MillibarsTolerance { get { return 1e-5; } } - protected virtual double MillimetersOfMercuryTolerance { get { return 1e-5; } } - protected virtual double MillipascalsTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double PascalsTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerSquareInchTolerance { get { return 1e-5; } } - protected virtual double PoundsPerInchSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double PsiTolerance { get { return 1e-5; } } - protected virtual double TechnicalAtmospheresTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerSquareMillimeterTolerance { get { return 1e-5; } } - protected virtual double TorrsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void PascalToPressureUnits() - { - Pressure pascal = Pressure.FromPascals(1); - AssertEx.EqualTolerance(AtmospheresInOnePascal, pascal.Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(BarsInOnePascal, pascal.Bars, BarsTolerance); - AssertEx.EqualTolerance(CentibarsInOnePascal, pascal.Centibars, CentibarsTolerance); - AssertEx.EqualTolerance(DecapascalsInOnePascal, pascal.Decapascals, DecapascalsTolerance); - AssertEx.EqualTolerance(DecibarsInOnePascal, pascal.Decibars, DecibarsTolerance); - AssertEx.EqualTolerance(DynesPerSquareCentimeterInOnePascal, pascal.DynesPerSquareCentimeter, DynesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(FeetOfHeadInOnePascal, pascal.FeetOfHead, FeetOfHeadTolerance); - AssertEx.EqualTolerance(GigapascalsInOnePascal, pascal.Gigapascals, GigapascalsTolerance); - AssertEx.EqualTolerance(HectopascalsInOnePascal, pascal.Hectopascals, HectopascalsTolerance); - AssertEx.EqualTolerance(InchesOfMercuryInOnePascal, pascal.InchesOfMercury, InchesOfMercuryTolerance); - AssertEx.EqualTolerance(KilobarsInOnePascal, pascal.Kilobars, KilobarsTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareCentimeterInOnePascal, pascal.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareMeterInOnePascal, pascal.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareMillimeterInOnePascal, pascal.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareCentimeterInOnePascal, pascal.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareMeterInOnePascal, pascal.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareMillimeterInOnePascal, pascal.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(KilopascalsInOnePascal, pascal.Kilopascals, KilopascalsTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerSquareFootInOnePascal, pascal.KilopoundsForcePerSquareFoot, KilopoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchInOnePascal, pascal.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(MegabarsInOnePascal, pascal.Megabars, MegabarsTolerance); - AssertEx.EqualTolerance(MeganewtonsPerSquareMeterInOnePascal, pascal.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MegapascalsInOnePascal, pascal.Megapascals, MegapascalsTolerance); - AssertEx.EqualTolerance(MetersOfHeadInOnePascal, pascal.MetersOfHead, MetersOfHeadTolerance); - AssertEx.EqualTolerance(MicrobarsInOnePascal, pascal.Microbars, MicrobarsTolerance); - AssertEx.EqualTolerance(MicropascalsInOnePascal, pascal.Micropascals, MicropascalsTolerance); - AssertEx.EqualTolerance(MillibarsInOnePascal, pascal.Millibars, MillibarsTolerance); - AssertEx.EqualTolerance(MillimetersOfMercuryInOnePascal, pascal.MillimetersOfMercury, MillimetersOfMercuryTolerance); - AssertEx.EqualTolerance(MillipascalsInOnePascal, pascal.Millipascals, MillipascalsTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareCentimeterInOnePascal, pascal.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareMeterInOnePascal, pascal.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareMillimeterInOnePascal, pascal.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(PascalsInOnePascal, pascal.Pascals, PascalsTolerance); - AssertEx.EqualTolerance(PoundsForcePerSquareFootInOnePascal, pascal.PoundsForcePerSquareFoot, PoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(PoundsForcePerSquareInchInOnePascal, pascal.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(PoundsPerInchSecondSquaredInOnePascal, pascal.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - AssertEx.EqualTolerance(PsiInOnePascal, pascal.Psi, PsiTolerance); - AssertEx.EqualTolerance(TechnicalAtmospheresInOnePascal, pascal.TechnicalAtmospheres, TechnicalAtmospheresTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareCentimeterInOnePascal, pascal.TonnesForcePerSquareCentimeter, TonnesForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareMeterInOnePascal, pascal.TonnesForcePerSquareMeter, TonnesForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareMillimeterInOnePascal, pascal.TonnesForcePerSquareMillimeter, TonnesForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(TorrsInOnePascal, pascal.Torrs, TorrsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Atmosphere).Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Bar).Bars, BarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Centibar).Centibars, CentibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Decapascal).Decapascals, DecapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Decibar).Decibars, DecibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.DynePerSquareCentimeter).DynesPerSquareCentimeter, DynesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.FootOfHead).FeetOfHead, FeetOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Gigapascal).Gigapascals, GigapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Hectopascal).Hectopascals, HectopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.InchOfMercury).InchesOfMercury, InchesOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Kilobar).Kilobars, KilobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilogramForcePerSquareCentimeter).KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilogramForcePerSquareMeter).KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilogramForcePerSquareMillimeter).KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilonewtonPerSquareCentimeter).KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilonewtonPerSquareMeter).KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilonewtonPerSquareMillimeter).KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Kilopascal).Kilopascals, KilopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilopoundForcePerSquareFoot).KilopoundsForcePerSquareFoot, KilopoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.KilopoundForcePerSquareInch).KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Megabar).Megabars, MegabarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.MeganewtonPerSquareMeter).MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Megapascal).Megapascals, MegapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.MeterOfHead).MetersOfHead, MetersOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Microbar).Microbars, MicrobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Micropascal).Micropascals, MicropascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Millibar).Millibars, MillibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.MillimeterOfMercury).MillimetersOfMercury, MillimetersOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Millipascal).Millipascals, MillipascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.NewtonPerSquareCentimeter).NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.NewtonPerSquareMeter).NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.NewtonPerSquareMillimeter).NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Pascal).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.PoundForcePerSquareFoot).PoundsForcePerSquareFoot, PoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.PoundForcePerSquareInch).PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.PoundPerInchSecondSquared).PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Psi).Psi, PsiTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.TechnicalAtmosphere).TechnicalAtmospheres, TechnicalAtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.TonneForcePerSquareCentimeter).TonnesForcePerSquareCentimeter, TonnesForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.TonneForcePerSquareMeter).TonnesForcePerSquareMeter, TonnesForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.TonneForcePerSquareMillimeter).TonnesForcePerSquareMillimeter, TonnesForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.From(1, PressureUnit.Torr).Torrs, TorrsTolerance); - } - - [Fact] - public void As() - { - var pascal = Pressure.FromPascals(1); - AssertEx.EqualTolerance(AtmospheresInOnePascal, pascal.As(PressureUnit.Atmosphere), AtmospheresTolerance); - AssertEx.EqualTolerance(BarsInOnePascal, pascal.As(PressureUnit.Bar), BarsTolerance); - AssertEx.EqualTolerance(CentibarsInOnePascal, pascal.As(PressureUnit.Centibar), CentibarsTolerance); - AssertEx.EqualTolerance(DecapascalsInOnePascal, pascal.As(PressureUnit.Decapascal), DecapascalsTolerance); - AssertEx.EqualTolerance(DecibarsInOnePascal, pascal.As(PressureUnit.Decibar), DecibarsTolerance); - AssertEx.EqualTolerance(DynesPerSquareCentimeterInOnePascal, pascal.As(PressureUnit.DynePerSquareCentimeter), DynesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(FeetOfHeadInOnePascal, pascal.As(PressureUnit.FootOfHead), FeetOfHeadTolerance); - AssertEx.EqualTolerance(GigapascalsInOnePascal, pascal.As(PressureUnit.Gigapascal), GigapascalsTolerance); - AssertEx.EqualTolerance(HectopascalsInOnePascal, pascal.As(PressureUnit.Hectopascal), HectopascalsTolerance); - AssertEx.EqualTolerance(InchesOfMercuryInOnePascal, pascal.As(PressureUnit.InchOfMercury), InchesOfMercuryTolerance); - AssertEx.EqualTolerance(KilobarsInOnePascal, pascal.As(PressureUnit.Kilobar), KilobarsTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareCentimeterInOnePascal, pascal.As(PressureUnit.KilogramForcePerSquareCentimeter), KilogramsForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareMeterInOnePascal, pascal.As(PressureUnit.KilogramForcePerSquareMeter), KilogramsForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerSquareMillimeterInOnePascal, pascal.As(PressureUnit.KilogramForcePerSquareMillimeter), KilogramsForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareCentimeterInOnePascal, pascal.As(PressureUnit.KilonewtonPerSquareCentimeter), KilonewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareMeterInOnePascal, pascal.As(PressureUnit.KilonewtonPerSquareMeter), KilonewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerSquareMillimeterInOnePascal, pascal.As(PressureUnit.KilonewtonPerSquareMillimeter), KilonewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(KilopascalsInOnePascal, pascal.As(PressureUnit.Kilopascal), KilopascalsTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerSquareFootInOnePascal, pascal.As(PressureUnit.KilopoundForcePerSquareFoot), KilopoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchInOnePascal, pascal.As(PressureUnit.KilopoundForcePerSquareInch), KilopoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(MegabarsInOnePascal, pascal.As(PressureUnit.Megabar), MegabarsTolerance); - AssertEx.EqualTolerance(MeganewtonsPerSquareMeterInOnePascal, pascal.As(PressureUnit.MeganewtonPerSquareMeter), MeganewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(MegapascalsInOnePascal, pascal.As(PressureUnit.Megapascal), MegapascalsTolerance); - AssertEx.EqualTolerance(MetersOfHeadInOnePascal, pascal.As(PressureUnit.MeterOfHead), MetersOfHeadTolerance); - AssertEx.EqualTolerance(MicrobarsInOnePascal, pascal.As(PressureUnit.Microbar), MicrobarsTolerance); - AssertEx.EqualTolerance(MicropascalsInOnePascal, pascal.As(PressureUnit.Micropascal), MicropascalsTolerance); - AssertEx.EqualTolerance(MillibarsInOnePascal, pascal.As(PressureUnit.Millibar), MillibarsTolerance); - AssertEx.EqualTolerance(MillimetersOfMercuryInOnePascal, pascal.As(PressureUnit.MillimeterOfMercury), MillimetersOfMercuryTolerance); - AssertEx.EqualTolerance(MillipascalsInOnePascal, pascal.As(PressureUnit.Millipascal), MillipascalsTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareCentimeterInOnePascal, pascal.As(PressureUnit.NewtonPerSquareCentimeter), NewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareMeterInOnePascal, pascal.As(PressureUnit.NewtonPerSquareMeter), NewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerSquareMillimeterInOnePascal, pascal.As(PressureUnit.NewtonPerSquareMillimeter), NewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(PascalsInOnePascal, pascal.As(PressureUnit.Pascal), PascalsTolerance); - AssertEx.EqualTolerance(PoundsForcePerSquareFootInOnePascal, pascal.As(PressureUnit.PoundForcePerSquareFoot), PoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(PoundsForcePerSquareInchInOnePascal, pascal.As(PressureUnit.PoundForcePerSquareInch), PoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(PoundsPerInchSecondSquaredInOnePascal, pascal.As(PressureUnit.PoundPerInchSecondSquared), PoundsPerInchSecondSquaredTolerance); - AssertEx.EqualTolerance(PsiInOnePascal, pascal.As(PressureUnit.Psi), PsiTolerance); - AssertEx.EqualTolerance(TechnicalAtmospheresInOnePascal, pascal.As(PressureUnit.TechnicalAtmosphere), TechnicalAtmospheresTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareCentimeterInOnePascal, pascal.As(PressureUnit.TonneForcePerSquareCentimeter), TonnesForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareMeterInOnePascal, pascal.As(PressureUnit.TonneForcePerSquareMeter), TonnesForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerSquareMillimeterInOnePascal, pascal.As(PressureUnit.TonneForcePerSquareMillimeter), TonnesForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(TorrsInOnePascal, pascal.As(PressureUnit.Torr), TorrsTolerance); - } - - [Fact] - public void ToUnit() - { - var pascal = Pressure.FromPascals(1); - - var atmosphereQuantity = pascal.ToUnit(PressureUnit.Atmosphere); - AssertEx.EqualTolerance(AtmospheresInOnePascal, (double)atmosphereQuantity.Value, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, atmosphereQuantity.Unit); - - var barQuantity = pascal.ToUnit(PressureUnit.Bar); - AssertEx.EqualTolerance(BarsInOnePascal, (double)barQuantity.Value, BarsTolerance); - Assert.Equal(PressureUnit.Bar, barQuantity.Unit); - - var centibarQuantity = pascal.ToUnit(PressureUnit.Centibar); - AssertEx.EqualTolerance(CentibarsInOnePascal, (double)centibarQuantity.Value, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, centibarQuantity.Unit); - - var decapascalQuantity = pascal.ToUnit(PressureUnit.Decapascal); - AssertEx.EqualTolerance(DecapascalsInOnePascal, (double)decapascalQuantity.Value, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, decapascalQuantity.Unit); - - var decibarQuantity = pascal.ToUnit(PressureUnit.Decibar); - AssertEx.EqualTolerance(DecibarsInOnePascal, (double)decibarQuantity.Value, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, decibarQuantity.Unit); - - var dynepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.DynePerSquareCentimeter); - AssertEx.EqualTolerance(DynesPerSquareCentimeterInOnePascal, (double)dynepersquarecentimeterQuantity.Value, DynesPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.DynePerSquareCentimeter, dynepersquarecentimeterQuantity.Unit); - - var footofheadQuantity = pascal.ToUnit(PressureUnit.FootOfHead); - AssertEx.EqualTolerance(FeetOfHeadInOnePascal, (double)footofheadQuantity.Value, FeetOfHeadTolerance); - Assert.Equal(PressureUnit.FootOfHead, footofheadQuantity.Unit); - - var gigapascalQuantity = pascal.ToUnit(PressureUnit.Gigapascal); - AssertEx.EqualTolerance(GigapascalsInOnePascal, (double)gigapascalQuantity.Value, GigapascalsTolerance); - Assert.Equal(PressureUnit.Gigapascal, gigapascalQuantity.Unit); - - var hectopascalQuantity = pascal.ToUnit(PressureUnit.Hectopascal); - AssertEx.EqualTolerance(HectopascalsInOnePascal, (double)hectopascalQuantity.Value, HectopascalsTolerance); - Assert.Equal(PressureUnit.Hectopascal, hectopascalQuantity.Unit); - - var inchofmercuryQuantity = pascal.ToUnit(PressureUnit.InchOfMercury); - AssertEx.EqualTolerance(InchesOfMercuryInOnePascal, (double)inchofmercuryQuantity.Value, InchesOfMercuryTolerance); - Assert.Equal(PressureUnit.InchOfMercury, inchofmercuryQuantity.Unit); - - var kilobarQuantity = pascal.ToUnit(PressureUnit.Kilobar); - AssertEx.EqualTolerance(KilobarsInOnePascal, (double)kilobarQuantity.Value, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, kilobarQuantity.Unit); - - var kilogramforcepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareCentimeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareCentimeterInOnePascal, (double)kilogramforcepersquarecentimeterQuantity.Value, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, kilogramforcepersquarecentimeterQuantity.Unit); - - var kilogramforcepersquaremeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareMeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareMeterInOnePascal, (double)kilogramforcepersquaremeterQuantity.Value, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, kilogramforcepersquaremeterQuantity.Unit); - - var kilogramforcepersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.KilogramForcePerSquareMillimeter); - AssertEx.EqualTolerance(KilogramsForcePerSquareMillimeterInOnePascal, (double)kilogramforcepersquaremillimeterQuantity.Value, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, kilogramforcepersquaremillimeterQuantity.Unit); - - var kilonewtonpersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareCentimeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareCentimeterInOnePascal, (double)kilonewtonpersquarecentimeterQuantity.Value, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, kilonewtonpersquarecentimeterQuantity.Unit); - - var kilonewtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareMeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareMeterInOnePascal, (double)kilonewtonpersquaremeterQuantity.Value, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, kilonewtonpersquaremeterQuantity.Unit); - - var kilonewtonpersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.KilonewtonPerSquareMillimeter); - AssertEx.EqualTolerance(KilonewtonsPerSquareMillimeterInOnePascal, (double)kilonewtonpersquaremillimeterQuantity.Value, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, kilonewtonpersquaremillimeterQuantity.Unit); - - var kilopascalQuantity = pascal.ToUnit(PressureUnit.Kilopascal); - AssertEx.EqualTolerance(KilopascalsInOnePascal, (double)kilopascalQuantity.Value, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, kilopascalQuantity.Unit); - - var kilopoundforcepersquarefootQuantity = pascal.ToUnit(PressureUnit.KilopoundForcePerSquareFoot); - AssertEx.EqualTolerance(KilopoundsForcePerSquareFootInOnePascal, (double)kilopoundforcepersquarefootQuantity.Value, KilopoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareFoot, kilopoundforcepersquarefootQuantity.Unit); - - var kilopoundforcepersquareinchQuantity = pascal.ToUnit(PressureUnit.KilopoundForcePerSquareInch); - AssertEx.EqualTolerance(KilopoundsForcePerSquareInchInOnePascal, (double)kilopoundforcepersquareinchQuantity.Value, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, kilopoundforcepersquareinchQuantity.Unit); - - var megabarQuantity = pascal.ToUnit(PressureUnit.Megabar); - AssertEx.EqualTolerance(MegabarsInOnePascal, (double)megabarQuantity.Value, MegabarsTolerance); - Assert.Equal(PressureUnit.Megabar, megabarQuantity.Unit); - - var meganewtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.MeganewtonPerSquareMeter); - AssertEx.EqualTolerance(MeganewtonsPerSquareMeterInOnePascal, (double)meganewtonpersquaremeterQuantity.Value, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, meganewtonpersquaremeterQuantity.Unit); - - var megapascalQuantity = pascal.ToUnit(PressureUnit.Megapascal); - AssertEx.EqualTolerance(MegapascalsInOnePascal, (double)megapascalQuantity.Value, MegapascalsTolerance); - Assert.Equal(PressureUnit.Megapascal, megapascalQuantity.Unit); - - var meterofheadQuantity = pascal.ToUnit(PressureUnit.MeterOfHead); - AssertEx.EqualTolerance(MetersOfHeadInOnePascal, (double)meterofheadQuantity.Value, MetersOfHeadTolerance); - Assert.Equal(PressureUnit.MeterOfHead, meterofheadQuantity.Unit); - - var microbarQuantity = pascal.ToUnit(PressureUnit.Microbar); - AssertEx.EqualTolerance(MicrobarsInOnePascal, (double)microbarQuantity.Value, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, microbarQuantity.Unit); - - var micropascalQuantity = pascal.ToUnit(PressureUnit.Micropascal); - AssertEx.EqualTolerance(MicropascalsInOnePascal, (double)micropascalQuantity.Value, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, micropascalQuantity.Unit); - - var millibarQuantity = pascal.ToUnit(PressureUnit.Millibar); - AssertEx.EqualTolerance(MillibarsInOnePascal, (double)millibarQuantity.Value, MillibarsTolerance); - Assert.Equal(PressureUnit.Millibar, millibarQuantity.Unit); - - var millimeterofmercuryQuantity = pascal.ToUnit(PressureUnit.MillimeterOfMercury); - AssertEx.EqualTolerance(MillimetersOfMercuryInOnePascal, (double)millimeterofmercuryQuantity.Value, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, millimeterofmercuryQuantity.Unit); - - var millipascalQuantity = pascal.ToUnit(PressureUnit.Millipascal); - AssertEx.EqualTolerance(MillipascalsInOnePascal, (double)millipascalQuantity.Value, MillipascalsTolerance); - Assert.Equal(PressureUnit.Millipascal, millipascalQuantity.Unit); - - var newtonpersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareCentimeter); - AssertEx.EqualTolerance(NewtonsPerSquareCentimeterInOnePascal, (double)newtonpersquarecentimeterQuantity.Value, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, newtonpersquarecentimeterQuantity.Unit); - - var newtonpersquaremeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareMeter); - AssertEx.EqualTolerance(NewtonsPerSquareMeterInOnePascal, (double)newtonpersquaremeterQuantity.Value, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, newtonpersquaremeterQuantity.Unit); - - var newtonpersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.NewtonPerSquareMillimeter); - AssertEx.EqualTolerance(NewtonsPerSquareMillimeterInOnePascal, (double)newtonpersquaremillimeterQuantity.Value, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, newtonpersquaremillimeterQuantity.Unit); - - var pascalQuantity = pascal.ToUnit(PressureUnit.Pascal); - AssertEx.EqualTolerance(PascalsInOnePascal, (double)pascalQuantity.Value, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, pascalQuantity.Unit); - - var poundforcepersquarefootQuantity = pascal.ToUnit(PressureUnit.PoundForcePerSquareFoot); - AssertEx.EqualTolerance(PoundsForcePerSquareFootInOnePascal, (double)poundforcepersquarefootQuantity.Value, PoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareFoot, poundforcepersquarefootQuantity.Unit); - - var poundforcepersquareinchQuantity = pascal.ToUnit(PressureUnit.PoundForcePerSquareInch); - AssertEx.EqualTolerance(PoundsForcePerSquareInchInOnePascal, (double)poundforcepersquareinchQuantity.Value, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, poundforcepersquareinchQuantity.Unit); - - var poundperinchsecondsquaredQuantity = pascal.ToUnit(PressureUnit.PoundPerInchSecondSquared); - AssertEx.EqualTolerance(PoundsPerInchSecondSquaredInOnePascal, (double)poundperinchsecondsquaredQuantity.Value, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, poundperinchsecondsquaredQuantity.Unit); - - var psiQuantity = pascal.ToUnit(PressureUnit.Psi); - AssertEx.EqualTolerance(PsiInOnePascal, (double)psiQuantity.Value, PsiTolerance); - Assert.Equal(PressureUnit.Psi, psiQuantity.Unit); - - var technicalatmosphereQuantity = pascal.ToUnit(PressureUnit.TechnicalAtmosphere); - AssertEx.EqualTolerance(TechnicalAtmospheresInOnePascal, (double)technicalatmosphereQuantity.Value, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, technicalatmosphereQuantity.Unit); - - var tonneforcepersquarecentimeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareCentimeter); - AssertEx.EqualTolerance(TonnesForcePerSquareCentimeterInOnePascal, (double)tonneforcepersquarecentimeterQuantity.Value, TonnesForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareCentimeter, tonneforcepersquarecentimeterQuantity.Unit); - - var tonneforcepersquaremeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareMeter); - AssertEx.EqualTolerance(TonnesForcePerSquareMeterInOnePascal, (double)tonneforcepersquaremeterQuantity.Value, TonnesForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMeter, tonneforcepersquaremeterQuantity.Unit); - - var tonneforcepersquaremillimeterQuantity = pascal.ToUnit(PressureUnit.TonneForcePerSquareMillimeter); - AssertEx.EqualTolerance(TonnesForcePerSquareMillimeterInOnePascal, (double)tonneforcepersquaremillimeterQuantity.Value, TonnesForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMillimeter, tonneforcepersquaremillimeterQuantity.Unit); - - var torrQuantity = pascal.ToUnit(PressureUnit.Torr); - AssertEx.EqualTolerance(TorrsInOnePascal, (double)torrQuantity.Value, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, torrQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Pressure pascal = Pressure.FromPascals(1); - AssertEx.EqualTolerance(1, Pressure.FromAtmospheres(pascal.Atmospheres).Pascals, AtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.FromBars(pascal.Bars).Pascals, BarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromCentibars(pascal.Centibars).Pascals, CentibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDecapascals(pascal.Decapascals).Pascals, DecapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDecibars(pascal.Decibars).Pascals, DecibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDynesPerSquareCentimeter(pascal.DynesPerSquareCentimeter).Pascals, DynesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromFeetOfHead(pascal.FeetOfHead).Pascals, FeetOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.FromGigapascals(pascal.Gigapascals).Pascals, GigapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromHectopascals(pascal.Hectopascals).Pascals, HectopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromInchesOfMercury(pascal.InchesOfMercury).Pascals, InchesOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilobars(pascal.Kilobars).Pascals, KilobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareCentimeter(pascal.KilogramsForcePerSquareCentimeter).Pascals, KilogramsForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareMeter(pascal.KilogramsForcePerSquareMeter).Pascals, KilogramsForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareMillimeter(pascal.KilogramsForcePerSquareMillimeter).Pascals, KilogramsForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareCentimeter(pascal.KilonewtonsPerSquareCentimeter).Pascals, KilonewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareMeter(pascal.KilonewtonsPerSquareMeter).Pascals, KilonewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareMillimeter(pascal.KilonewtonsPerSquareMillimeter).Pascals, KilonewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopascals(pascal.Kilopascals).Pascals, KilopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopoundsForcePerSquareFoot(pascal.KilopoundsForcePerSquareFoot).Pascals, KilopoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopoundsForcePerSquareInch(pascal.KilopoundsForcePerSquareInch).Pascals, KilopoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMegabars(pascal.Megabars).Pascals, MegabarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMeganewtonsPerSquareMeter(pascal.MeganewtonsPerSquareMeter).Pascals, MeganewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMegapascals(pascal.Megapascals).Pascals, MegapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMetersOfHead(pascal.MetersOfHead).Pascals, MetersOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMicrobars(pascal.Microbars).Pascals, MicrobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMicropascals(pascal.Micropascals).Pascals, MicropascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillibars(pascal.Millibars).Pascals, MillibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillimetersOfMercury(pascal.MillimetersOfMercury).Pascals, MillimetersOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillipascals(pascal.Millipascals).Pascals, MillipascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareCentimeter(pascal.NewtonsPerSquareCentimeter).Pascals, NewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareMeter(pascal.NewtonsPerSquareMeter).Pascals, NewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareMillimeter(pascal.NewtonsPerSquareMillimeter).Pascals, NewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPascals(pascal.Pascals).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsForcePerSquareFoot(pascal.PoundsForcePerSquareFoot).Pascals, PoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsForcePerSquareInch(pascal.PoundsForcePerSquareInch).Pascals, PoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsPerInchSecondSquared(pascal.PoundsPerInchSecondSquared).Pascals, PoundsPerInchSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPsi(pascal.Psi).Pascals, PsiTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTechnicalAtmospheres(pascal.TechnicalAtmospheres).Pascals, TechnicalAtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareCentimeter(pascal.TonnesForcePerSquareCentimeter).Pascals, TonnesForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareMeter(pascal.TonnesForcePerSquareMeter).Pascals, TonnesForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareMillimeter(pascal.TonnesForcePerSquareMillimeter).Pascals, TonnesForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTorrs(pascal.Torrs).Pascals, TorrsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Pressure v = Pressure.FromPascals(1); - AssertEx.EqualTolerance(-1, -v.Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (Pressure.FromPascals(3)-v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (v + v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(10, (v*10).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(10, (10*v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (Pressure.FromPascals(10)/5).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, Pressure.FromPascals(10)/Pressure.FromPascals(5), PascalsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Pressure onePascal = Pressure.FromPascals(1); - Pressure twoPascals = Pressure.FromPascals(2); - - Assert.True(onePascal < twoPascals); - Assert.True(onePascal <= twoPascals); - Assert.True(twoPascals > onePascal); - Assert.True(twoPascals >= onePascal); - - Assert.False(onePascal > twoPascals); - Assert.False(onePascal >= twoPascals); - Assert.False(twoPascals < onePascal); - Assert.False(twoPascals <= onePascal); - } - - [Fact] - public void CompareToIsImplemented() - { - Pressure pascal = Pressure.FromPascals(1); - Assert.Equal(0, pascal.CompareTo(pascal)); - Assert.True(pascal.CompareTo(Pressure.Zero) > 0); - Assert.True(Pressure.Zero.CompareTo(pascal) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Pressure pascal = Pressure.FromPascals(1); - Assert.Throws(() => pascal.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Pressure pascal = Pressure.FromPascals(1); - Assert.Throws(() => pascal.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Pressure a = Pressure.FromPascals(1); - Pressure b = Pressure.FromPascals(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Pressure v = Pressure.FromPascals(1); - Assert.True(v.Equals(Pressure.FromPascals(1), Pressure.FromPascals(PascalsTolerance))); - Assert.False(v.Equals(Pressure.Zero, Pressure.FromPascals(PascalsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Pressure pascal = Pressure.FromPascals(1); - Assert.False(pascal.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Pressure pascal = Pressure.FromPascals(1); - Assert.False(pascal.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureUnit.Undefined, Pressure.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/RatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/RatioTestsBase.g.cs deleted file mode 100644 index 0b1e156e0d..0000000000 --- a/UnitsNet.Tests/GeneratedCode/RatioTestsBase.g.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Ratio. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class RatioTestsBase - { - protected abstract double DecimalFractionsInOneDecimalFraction { get; } - protected abstract double PartsPerBillionInOneDecimalFraction { get; } - protected abstract double PartsPerMillionInOneDecimalFraction { get; } - protected abstract double PartsPerThousandInOneDecimalFraction { get; } - protected abstract double PartsPerTrillionInOneDecimalFraction { get; } - protected abstract double PercentInOneDecimalFraction { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DecimalFractionsTolerance { get { return 1e-5; } } - protected virtual double PartsPerBillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerMillionTolerance { get { return 1e-5; } } - protected virtual double PartsPerThousandTolerance { get { return 1e-5; } } - protected virtual double PartsPerTrillionTolerance { get { return 1e-5; } } - protected virtual double PercentTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DecimalFractionToRatioUnits() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, decimalfraction.DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, decimalfraction.PartsPerBillion, PartsPerBillionTolerance); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, decimalfraction.PartsPerMillion, PartsPerMillionTolerance); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, decimalfraction.PartsPerThousand, PartsPerThousandTolerance); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, decimalfraction.PartsPerTrillion, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, decimalfraction.Percent, PercentTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.DecimalFraction).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.PartPerBillion).PartsPerBillion, PartsPerBillionTolerance); - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.PartPerMillion).PartsPerMillion, PartsPerMillionTolerance); - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.PartPerThousand).PartsPerThousand, PartsPerThousandTolerance); - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.PartPerTrillion).PartsPerTrillion, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(1, Ratio.From(1, RatioUnit.Percent).Percent, PercentTolerance); - } - - [Fact] - public void As() - { - var decimalfraction = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, decimalfraction.As(RatioUnit.DecimalFraction), DecimalFractionsTolerance); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, decimalfraction.As(RatioUnit.PartPerBillion), PartsPerBillionTolerance); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, decimalfraction.As(RatioUnit.PartPerMillion), PartsPerMillionTolerance); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, decimalfraction.As(RatioUnit.PartPerThousand), PartsPerThousandTolerance); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, decimalfraction.As(RatioUnit.PartPerTrillion), PartsPerTrillionTolerance); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, decimalfraction.As(RatioUnit.Percent), PercentTolerance); - } - - [Fact] - public void ToUnit() - { - var decimalfraction = Ratio.FromDecimalFractions(1); - - var decimalfractionQuantity = decimalfraction.ToUnit(RatioUnit.DecimalFraction); - AssertEx.EqualTolerance(DecimalFractionsInOneDecimalFraction, (double)decimalfractionQuantity.Value, DecimalFractionsTolerance); - Assert.Equal(RatioUnit.DecimalFraction, decimalfractionQuantity.Unit); - - var partperbillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerBillion); - AssertEx.EqualTolerance(PartsPerBillionInOneDecimalFraction, (double)partperbillionQuantity.Value, PartsPerBillionTolerance); - Assert.Equal(RatioUnit.PartPerBillion, partperbillionQuantity.Unit); - - var partpermillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerMillion); - AssertEx.EqualTolerance(PartsPerMillionInOneDecimalFraction, (double)partpermillionQuantity.Value, PartsPerMillionTolerance); - Assert.Equal(RatioUnit.PartPerMillion, partpermillionQuantity.Unit); - - var partperthousandQuantity = decimalfraction.ToUnit(RatioUnit.PartPerThousand); - AssertEx.EqualTolerance(PartsPerThousandInOneDecimalFraction, (double)partperthousandQuantity.Value, PartsPerThousandTolerance); - Assert.Equal(RatioUnit.PartPerThousand, partperthousandQuantity.Unit); - - var partpertrillionQuantity = decimalfraction.ToUnit(RatioUnit.PartPerTrillion); - AssertEx.EqualTolerance(PartsPerTrillionInOneDecimalFraction, (double)partpertrillionQuantity.Value, PartsPerTrillionTolerance); - Assert.Equal(RatioUnit.PartPerTrillion, partpertrillionQuantity.Unit); - - var percentQuantity = decimalfraction.ToUnit(RatioUnit.Percent); - AssertEx.EqualTolerance(PercentInOneDecimalFraction, (double)percentQuantity.Value, PercentTolerance); - Assert.Equal(RatioUnit.Percent, percentQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(1, Ratio.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions, PartsPerBillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions, PartsPerMillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions, PartsPerThousandTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPercent(decimalfraction.Percent).DecimalFractions, PercentTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Ratio v = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(-1, -v.DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (Ratio.FromDecimalFractions(3)-v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (v + v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (v*10).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (10*v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (Ratio.FromDecimalFractions(10)/5).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, Ratio.FromDecimalFractions(10)/Ratio.FromDecimalFractions(5), DecimalFractionsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Ratio oneDecimalFraction = Ratio.FromDecimalFractions(1); - Ratio twoDecimalFractions = Ratio.FromDecimalFractions(2); - - Assert.True(oneDecimalFraction < twoDecimalFractions); - Assert.True(oneDecimalFraction <= twoDecimalFractions); - Assert.True(twoDecimalFractions > oneDecimalFraction); - Assert.True(twoDecimalFractions >= oneDecimalFraction); - - Assert.False(oneDecimalFraction > twoDecimalFractions); - Assert.False(oneDecimalFraction >= twoDecimalFractions); - Assert.False(twoDecimalFractions < oneDecimalFraction); - Assert.False(twoDecimalFractions <= oneDecimalFraction); - } - - [Fact] - public void CompareToIsImplemented() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.Equal(0, decimalfraction.CompareTo(decimalfraction)); - Assert.True(decimalfraction.CompareTo(Ratio.Zero) > 0); - Assert.True(Ratio.Zero.CompareTo(decimalfraction) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.Throws(() => decimalfraction.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.Throws(() => decimalfraction.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Ratio a = Ratio.FromDecimalFractions(1); - Ratio b = Ratio.FromDecimalFractions(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Ratio v = Ratio.FromDecimalFractions(1); - Assert.True(v.Equals(Ratio.FromDecimalFractions(1), Ratio.FromDecimalFractions(DecimalFractionsTolerance))); - Assert.False(v.Equals(Ratio.Zero, Ratio.FromDecimalFractions(DecimalFractionsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.False(decimalfraction.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.False(decimalfraction.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RatioUnit.Undefined, Ratio.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ReactiveEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ReactiveEnergyTestsBase.g.cs deleted file mode 100644 index d0deaa44aa..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ReactiveEnergyTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ReactiveEnergy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ReactiveEnergyTestsBase - { - protected abstract double KilovoltampereReactiveHoursInOneVoltampereReactiveHour { get; } - protected abstract double MegavoltampereReactiveHoursInOneVoltampereReactiveHour { get; } - protected abstract double VoltampereReactiveHoursInOneVoltampereReactiveHour { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilovoltampereReactiveHoursTolerance { get { return 1e-5; } } - protected virtual double MegavoltampereReactiveHoursTolerance { get { return 1e-5; } } - protected virtual double VoltampereReactiveHoursTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltampereReactiveHourToReactiveEnergyUnits() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(KilovoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.KilovoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(MegavoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.MegavoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(VoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ReactiveEnergy.From(1, ReactiveEnergyUnit.KilovoltampereReactiveHour).KilovoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ReactiveEnergy.From(1, ReactiveEnergyUnit.MegavoltampereReactiveHour).MegavoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ReactiveEnergy.From(1, ReactiveEnergyUnit.VoltampereReactiveHour).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - } - - [Fact] - public void As() - { - var voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(KilovoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.As(ReactiveEnergyUnit.KilovoltampereReactiveHour), KilovoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(MegavoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.As(ReactiveEnergyUnit.MegavoltampereReactiveHour), MegavoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(VoltampereReactiveHoursInOneVoltampereReactiveHour, voltamperereactivehour.As(ReactiveEnergyUnit.VoltampereReactiveHour), VoltampereReactiveHoursTolerance); - } - - [Fact] - public void ToUnit() - { - var voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - - var kilovoltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.KilovoltampereReactiveHour); - AssertEx.EqualTolerance(KilovoltampereReactiveHoursInOneVoltampereReactiveHour, (double)kilovoltamperereactivehourQuantity.Value, KilovoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.KilovoltampereReactiveHour, kilovoltamperereactivehourQuantity.Unit); - - var megavoltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.MegavoltampereReactiveHour); - AssertEx.EqualTolerance(MegavoltampereReactiveHoursInOneVoltampereReactiveHour, (double)megavoltamperereactivehourQuantity.Value, MegavoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.MegavoltampereReactiveHour, megavoltamperereactivehourQuantity.Unit); - - var voltamperereactivehourQuantity = voltamperereactivehour.ToUnit(ReactiveEnergyUnit.VoltampereReactiveHour); - AssertEx.EqualTolerance(VoltampereReactiveHoursInOneVoltampereReactiveHour, (double)voltamperereactivehourQuantity.Value, VoltampereReactiveHoursTolerance); - Assert.Equal(ReactiveEnergyUnit.VoltampereReactiveHour, voltamperereactivehourQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(1, ReactiveEnergy.FromKilovoltampereReactiveHours(voltamperereactivehour.KilovoltampereReactiveHours).VoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ReactiveEnergy.FromMegavoltampereReactiveHours(voltamperereactivehour.MegavoltampereReactiveHours).VoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ReactiveEnergy.FromVoltampereReactiveHours(voltamperereactivehour.VoltampereReactiveHours).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ReactiveEnergy v = ReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(-1, -v.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (ReactiveEnergy.FromVoltampereReactiveHours(3)-v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (ReactiveEnergy.FromVoltampereReactiveHours(10)/5).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, ReactiveEnergy.FromVoltampereReactiveHours(10)/ReactiveEnergy.FromVoltampereReactiveHours(5), VoltampereReactiveHoursTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ReactiveEnergy oneVoltampereReactiveHour = ReactiveEnergy.FromVoltampereReactiveHours(1); - ReactiveEnergy twoVoltampereReactiveHours = ReactiveEnergy.FromVoltampereReactiveHours(2); - - Assert.True(oneVoltampereReactiveHour < twoVoltampereReactiveHours); - Assert.True(oneVoltampereReactiveHour <= twoVoltampereReactiveHours); - Assert.True(twoVoltampereReactiveHours > oneVoltampereReactiveHour); - Assert.True(twoVoltampereReactiveHours >= oneVoltampereReactiveHour); - - Assert.False(oneVoltampereReactiveHour > twoVoltampereReactiveHours); - Assert.False(oneVoltampereReactiveHour >= twoVoltampereReactiveHours); - Assert.False(twoVoltampereReactiveHours < oneVoltampereReactiveHour); - Assert.False(twoVoltampereReactiveHours <= oneVoltampereReactiveHour); - } - - [Fact] - public void CompareToIsImplemented() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.Equal(0, voltamperereactivehour.CompareTo(voltamperereactivehour)); - Assert.True(voltamperereactivehour.CompareTo(ReactiveEnergy.Zero) > 0); - Assert.True(ReactiveEnergy.Zero.CompareTo(voltamperereactivehour) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.Throws(() => voltamperereactivehour.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.Throws(() => voltamperereactivehour.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ReactiveEnergy a = ReactiveEnergy.FromVoltampereReactiveHours(1); - ReactiveEnergy b = ReactiveEnergy.FromVoltampereReactiveHours(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ReactiveEnergy v = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.True(v.Equals(ReactiveEnergy.FromVoltampereReactiveHours(1), ReactiveEnergy.FromVoltampereReactiveHours(VoltampereReactiveHoursTolerance))); - Assert.False(v.Equals(ReactiveEnergy.Zero, ReactiveEnergy.FromVoltampereReactiveHours(VoltampereReactiveHoursTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.False(voltamperereactivehour.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ReactiveEnergy voltamperereactivehour = ReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.False(voltamperereactivehour.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReactiveEnergyUnit.Undefined, ReactiveEnergy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ReactivePowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ReactivePowerTestsBase.g.cs deleted file mode 100644 index 627bdaa5d3..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ReactivePowerTestsBase.g.cs +++ /dev/null @@ -1,227 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ReactivePower. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ReactivePowerTestsBase - { - protected abstract double GigavoltamperesReactiveInOneVoltampereReactive { get; } - protected abstract double KilovoltamperesReactiveInOneVoltampereReactive { get; } - protected abstract double MegavoltamperesReactiveInOneVoltampereReactive { get; } - protected abstract double VoltamperesReactiveInOneVoltampereReactive { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double GigavoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double KilovoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double MegavoltamperesReactiveTolerance { get { return 1e-5; } } - protected virtual double VoltamperesReactiveTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void VoltampereReactiveToReactivePowerUnits() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(GigavoltamperesReactiveInOneVoltampereReactive, voltamperereactive.GigavoltamperesReactive, GigavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(KilovoltamperesReactiveInOneVoltampereReactive, voltamperereactive.KilovoltamperesReactive, KilovoltamperesReactiveTolerance); - AssertEx.EqualTolerance(MegavoltamperesReactiveInOneVoltampereReactive, voltamperereactive.MegavoltamperesReactive, MegavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(VoltamperesReactiveInOneVoltampereReactive, voltamperereactive.VoltamperesReactive, VoltamperesReactiveTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ReactivePower.From(1, ReactivePowerUnit.GigavoltampereReactive).GigavoltamperesReactive, GigavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.From(1, ReactivePowerUnit.KilovoltampereReactive).KilovoltamperesReactive, KilovoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.From(1, ReactivePowerUnit.MegavoltampereReactive).MegavoltamperesReactive, MegavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.From(1, ReactivePowerUnit.VoltampereReactive).VoltamperesReactive, VoltamperesReactiveTolerance); - } - - [Fact] - public void As() - { - var voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(GigavoltamperesReactiveInOneVoltampereReactive, voltamperereactive.As(ReactivePowerUnit.GigavoltampereReactive), GigavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(KilovoltamperesReactiveInOneVoltampereReactive, voltamperereactive.As(ReactivePowerUnit.KilovoltampereReactive), KilovoltamperesReactiveTolerance); - AssertEx.EqualTolerance(MegavoltamperesReactiveInOneVoltampereReactive, voltamperereactive.As(ReactivePowerUnit.MegavoltampereReactive), MegavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(VoltamperesReactiveInOneVoltampereReactive, voltamperereactive.As(ReactivePowerUnit.VoltampereReactive), VoltamperesReactiveTolerance); - } - - [Fact] - public void ToUnit() - { - var voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - - var gigavoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.GigavoltampereReactive); - AssertEx.EqualTolerance(GigavoltamperesReactiveInOneVoltampereReactive, (double)gigavoltamperereactiveQuantity.Value, GigavoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.GigavoltampereReactive, gigavoltamperereactiveQuantity.Unit); - - var kilovoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.KilovoltampereReactive); - AssertEx.EqualTolerance(KilovoltamperesReactiveInOneVoltampereReactive, (double)kilovoltamperereactiveQuantity.Value, KilovoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.KilovoltampereReactive, kilovoltamperereactiveQuantity.Unit); - - var megavoltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.MegavoltampereReactive); - AssertEx.EqualTolerance(MegavoltamperesReactiveInOneVoltampereReactive, (double)megavoltamperereactiveQuantity.Value, MegavoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.MegavoltampereReactive, megavoltamperereactiveQuantity.Unit); - - var voltamperereactiveQuantity = voltamperereactive.ToUnit(ReactivePowerUnit.VoltampereReactive); - AssertEx.EqualTolerance(VoltamperesReactiveInOneVoltampereReactive, (double)voltamperereactiveQuantity.Value, VoltamperesReactiveTolerance); - Assert.Equal(ReactivePowerUnit.VoltampereReactive, voltamperereactiveQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(1, ReactivePower.FromGigavoltamperesReactive(voltamperereactive.GigavoltamperesReactive).VoltamperesReactive, GigavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.FromKilovoltamperesReactive(voltamperereactive.KilovoltamperesReactive).VoltamperesReactive, KilovoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.FromMegavoltamperesReactive(voltamperereactive.MegavoltamperesReactive).VoltamperesReactive, MegavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ReactivePower.FromVoltamperesReactive(voltamperereactive.VoltamperesReactive).VoltamperesReactive, VoltamperesReactiveTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ReactivePower v = ReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(-1, -v.VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (ReactivePower.FromVoltamperesReactive(3)-v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (ReactivePower.FromVoltamperesReactive(10)/5).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, ReactivePower.FromVoltamperesReactive(10)/ReactivePower.FromVoltamperesReactive(5), VoltamperesReactiveTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ReactivePower oneVoltampereReactive = ReactivePower.FromVoltamperesReactive(1); - ReactivePower twoVoltamperesReactive = ReactivePower.FromVoltamperesReactive(2); - - Assert.True(oneVoltampereReactive < twoVoltamperesReactive); - Assert.True(oneVoltampereReactive <= twoVoltamperesReactive); - Assert.True(twoVoltamperesReactive > oneVoltampereReactive); - Assert.True(twoVoltamperesReactive >= oneVoltampereReactive); - - Assert.False(oneVoltampereReactive > twoVoltamperesReactive); - Assert.False(oneVoltampereReactive >= twoVoltamperesReactive); - Assert.False(twoVoltamperesReactive < oneVoltampereReactive); - Assert.False(twoVoltamperesReactive <= oneVoltampereReactive); - } - - [Fact] - public void CompareToIsImplemented() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - Assert.Equal(0, voltamperereactive.CompareTo(voltamperereactive)); - Assert.True(voltamperereactive.CompareTo(ReactivePower.Zero) > 0); - Assert.True(ReactivePower.Zero.CompareTo(voltamperereactive) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - Assert.Throws(() => voltamperereactive.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - Assert.Throws(() => voltamperereactive.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ReactivePower a = ReactivePower.FromVoltamperesReactive(1); - ReactivePower b = ReactivePower.FromVoltamperesReactive(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ReactivePower v = ReactivePower.FromVoltamperesReactive(1); - Assert.True(v.Equals(ReactivePower.FromVoltamperesReactive(1), ReactivePower.FromVoltamperesReactive(VoltamperesReactiveTolerance))); - Assert.False(v.Equals(ReactivePower.Zero, ReactivePower.FromVoltamperesReactive(VoltamperesReactiveTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - Assert.False(voltamperereactive.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ReactivePower voltamperereactive = ReactivePower.FromVoltamperesReactive(1); - Assert.False(voltamperereactive.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReactivePowerUnit.Undefined, ReactivePower.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/RotationalAccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/RotationalAccelerationTestsBase.g.cs deleted file mode 100644 index c22d688973..0000000000 --- a/UnitsNet.Tests/GeneratedCode/RotationalAccelerationTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of RotationalAcceleration. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class RotationalAccelerationTestsBase - { - protected abstract double DegreesPerSecondSquaredInOneRadianPerSecondSquared { get; } - protected abstract double RadiansPerSecondSquaredInOneRadianPerSecondSquared { get; } - protected abstract double RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondSquaredTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerMinutePerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void RadianPerSecondSquaredToRotationalAccelerationUnits() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(DegreesPerSecondSquaredInOneRadianPerSecondSquared, radianpersecondsquared.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(RadiansPerSecondSquaredInOneRadianPerSecondSquared, radianpersecondsquared.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared, radianpersecondsquared.RevolutionsPerMinutePerSecond, RevolutionsPerMinutePerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, RotationalAcceleration.From(1, RotationalAccelerationUnit.DegreePerSecondSquared).DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.From(1, RotationalAccelerationUnit.RadianPerSecondSquared).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.From(1, RotationalAccelerationUnit.RevolutionPerMinutePerSecond).RevolutionsPerMinutePerSecond, RevolutionsPerMinutePerSecondTolerance); - } - - [Fact] - public void As() - { - var radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(DegreesPerSecondSquaredInOneRadianPerSecondSquared, radianpersecondsquared.As(RotationalAccelerationUnit.DegreePerSecondSquared), DegreesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(RadiansPerSecondSquaredInOneRadianPerSecondSquared, radianpersecondsquared.As(RotationalAccelerationUnit.RadianPerSecondSquared), RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared, radianpersecondsquared.As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond), RevolutionsPerMinutePerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - - var degreepersecondsquaredQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.DegreePerSecondSquared); - AssertEx.EqualTolerance(DegreesPerSecondSquaredInOneRadianPerSecondSquared, (double)degreepersecondsquaredQuantity.Value, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, degreepersecondsquaredQuantity.Unit); - - var radianpersecondsquaredQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared); - AssertEx.EqualTolerance(RadiansPerSecondSquaredInOneRadianPerSecondSquared, (double)radianpersecondsquaredQuantity.Value, RadiansPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, radianpersecondsquaredQuantity.Unit); - - var revolutionperminutepersecondQuantity = radianpersecondsquared.ToUnit(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - AssertEx.EqualTolerance(RevolutionsPerMinutePerSecondInOneRadianPerSecondSquared, (double)revolutionperminutepersecondQuantity.Value, RevolutionsPerMinutePerSecondTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, revolutionperminutepersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromDegreesPerSecondSquared(radianpersecondsquared.DegreesPerSecondSquared).RadiansPerSecondSquared, DegreesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromRadiansPerSecondSquared(radianpersecondsquared.RadiansPerSecondSquared).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromRevolutionsPerMinutePerSecond(radianpersecondsquared.RevolutionsPerMinutePerSecond).RadiansPerSecondSquared, RevolutionsPerMinutePerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - RotationalAcceleration v = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(-1, -v.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (RotationalAcceleration.FromRadiansPerSecondSquared(3)-v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (RotationalAcceleration.FromRadiansPerSecondSquared(10)/5).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, RotationalAcceleration.FromRadiansPerSecondSquared(10)/RotationalAcceleration.FromRadiansPerSecondSquared(5), RadiansPerSecondSquaredTolerance); - } - - [Fact] - public void ComparisonOperators() - { - RotationalAcceleration oneRadianPerSecondSquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - RotationalAcceleration twoRadiansPerSecondSquared = RotationalAcceleration.FromRadiansPerSecondSquared(2); - - Assert.True(oneRadianPerSecondSquared < twoRadiansPerSecondSquared); - Assert.True(oneRadianPerSecondSquared <= twoRadiansPerSecondSquared); - Assert.True(twoRadiansPerSecondSquared > oneRadianPerSecondSquared); - Assert.True(twoRadiansPerSecondSquared >= oneRadianPerSecondSquared); - - Assert.False(oneRadianPerSecondSquared > twoRadiansPerSecondSquared); - Assert.False(oneRadianPerSecondSquared >= twoRadiansPerSecondSquared); - Assert.False(twoRadiansPerSecondSquared < oneRadianPerSecondSquared); - Assert.False(twoRadiansPerSecondSquared <= oneRadianPerSecondSquared); - } - - [Fact] - public void CompareToIsImplemented() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.Equal(0, radianpersecondsquared.CompareTo(radianpersecondsquared)); - Assert.True(radianpersecondsquared.CompareTo(RotationalAcceleration.Zero) > 0); - Assert.True(RotationalAcceleration.Zero.CompareTo(radianpersecondsquared) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.Throws(() => radianpersecondsquared.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.Throws(() => radianpersecondsquared.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - RotationalAcceleration a = RotationalAcceleration.FromRadiansPerSecondSquared(1); - RotationalAcceleration b = RotationalAcceleration.FromRadiansPerSecondSquared(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - RotationalAcceleration v = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.True(v.Equals(RotationalAcceleration.FromRadiansPerSecondSquared(1), RotationalAcceleration.FromRadiansPerSecondSquared(RadiansPerSecondSquaredTolerance))); - Assert.False(v.Equals(RotationalAcceleration.Zero, RotationalAcceleration.FromRadiansPerSecondSquared(RadiansPerSecondSquaredTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.False(radianpersecondsquared.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.False(radianpersecondsquared.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalAccelerationUnit.Undefined, RotationalAcceleration.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/RotationalSpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/RotationalSpeedTestsBase.g.cs deleted file mode 100644 index 3ad5a6df0d..0000000000 --- a/UnitsNet.Tests/GeneratedCode/RotationalSpeedTestsBase.g.cs +++ /dev/null @@ -1,317 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of RotationalSpeed. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class RotationalSpeedTestsBase - { - protected abstract double CentiradiansPerSecondInOneRadianPerSecond { get; } - protected abstract double DeciradiansPerSecondInOneRadianPerSecond { get; } - protected abstract double DegreesPerMinuteInOneRadianPerSecond { get; } - protected abstract double DegreesPerSecondInOneRadianPerSecond { get; } - protected abstract double MicrodegreesPerSecondInOneRadianPerSecond { get; } - protected abstract double MicroradiansPerSecondInOneRadianPerSecond { get; } - protected abstract double MillidegreesPerSecondInOneRadianPerSecond { get; } - protected abstract double MilliradiansPerSecondInOneRadianPerSecond { get; } - protected abstract double NanodegreesPerSecondInOneRadianPerSecond { get; } - protected abstract double NanoradiansPerSecondInOneRadianPerSecond { get; } - protected abstract double RadiansPerSecondInOneRadianPerSecond { get; } - protected abstract double RevolutionsPerMinuteInOneRadianPerSecond { get; } - protected abstract double RevolutionsPerSecondInOneRadianPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentiradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double DeciradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double DegreesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicroradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillidegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MilliradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanodegreesPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanoradiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double RadiansPerSecondTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double RevolutionsPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void RadianPerSecondToRotationalSpeedUnits() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(CentiradiansPerSecondInOneRadianPerSecond, radianpersecond.CentiradiansPerSecond, CentiradiansPerSecondTolerance); - AssertEx.EqualTolerance(DeciradiansPerSecondInOneRadianPerSecond, radianpersecond.DeciradiansPerSecond, DeciradiansPerSecondTolerance); - AssertEx.EqualTolerance(DegreesPerMinuteInOneRadianPerSecond, radianpersecond.DegreesPerMinute, DegreesPerMinuteTolerance); - AssertEx.EqualTolerance(DegreesPerSecondInOneRadianPerSecond, radianpersecond.DegreesPerSecond, DegreesPerSecondTolerance); - AssertEx.EqualTolerance(MicrodegreesPerSecondInOneRadianPerSecond, radianpersecond.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - AssertEx.EqualTolerance(MicroradiansPerSecondInOneRadianPerSecond, radianpersecond.MicroradiansPerSecond, MicroradiansPerSecondTolerance); - AssertEx.EqualTolerance(MillidegreesPerSecondInOneRadianPerSecond, radianpersecond.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - AssertEx.EqualTolerance(MilliradiansPerSecondInOneRadianPerSecond, radianpersecond.MilliradiansPerSecond, MilliradiansPerSecondTolerance); - AssertEx.EqualTolerance(NanodegreesPerSecondInOneRadianPerSecond, radianpersecond.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - AssertEx.EqualTolerance(NanoradiansPerSecondInOneRadianPerSecond, radianpersecond.NanoradiansPerSecond, NanoradiansPerSecondTolerance); - AssertEx.EqualTolerance(RadiansPerSecondInOneRadianPerSecond, radianpersecond.RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(RevolutionsPerMinuteInOneRadianPerSecond, radianpersecond.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - AssertEx.EqualTolerance(RevolutionsPerSecondInOneRadianPerSecond, radianpersecond.RevolutionsPerSecond, RevolutionsPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.CentiradianPerSecond).CentiradiansPerSecond, CentiradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.DeciradianPerSecond).DeciradiansPerSecond, DeciradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.DegreePerMinute).DegreesPerMinute, DegreesPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.DegreePerSecond).DegreesPerSecond, DegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.MicrodegreePerSecond).MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.MicroradianPerSecond).MicroradiansPerSecond, MicroradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.MillidegreePerSecond).MillidegreesPerSecond, MillidegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.MilliradianPerSecond).MilliradiansPerSecond, MilliradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.NanodegreePerSecond).NanodegreesPerSecond, NanodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.NanoradianPerSecond).NanoradiansPerSecond, NanoradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.RadianPerSecond).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.RevolutionPerMinute).RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.From(1, RotationalSpeedUnit.RevolutionPerSecond).RevolutionsPerSecond, RevolutionsPerSecondTolerance); - } - - [Fact] - public void As() - { - var radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(CentiradiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.CentiradianPerSecond), CentiradiansPerSecondTolerance); - AssertEx.EqualTolerance(DeciradiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.DeciradianPerSecond), DeciradiansPerSecondTolerance); - AssertEx.EqualTolerance(DegreesPerMinuteInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.DegreePerMinute), DegreesPerMinuteTolerance); - AssertEx.EqualTolerance(DegreesPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.DegreePerSecond), DegreesPerSecondTolerance); - AssertEx.EqualTolerance(MicrodegreesPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.MicrodegreePerSecond), MicrodegreesPerSecondTolerance); - AssertEx.EqualTolerance(MicroradiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.MicroradianPerSecond), MicroradiansPerSecondTolerance); - AssertEx.EqualTolerance(MillidegreesPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.MillidegreePerSecond), MillidegreesPerSecondTolerance); - AssertEx.EqualTolerance(MilliradiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.MilliradianPerSecond), MilliradiansPerSecondTolerance); - AssertEx.EqualTolerance(NanodegreesPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.NanodegreePerSecond), NanodegreesPerSecondTolerance); - AssertEx.EqualTolerance(NanoradiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.NanoradianPerSecond), NanoradiansPerSecondTolerance); - AssertEx.EqualTolerance(RadiansPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.RadianPerSecond), RadiansPerSecondTolerance); - AssertEx.EqualTolerance(RevolutionsPerMinuteInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.RevolutionPerMinute), RevolutionsPerMinuteTolerance); - AssertEx.EqualTolerance(RevolutionsPerSecondInOneRadianPerSecond, radianpersecond.As(RotationalSpeedUnit.RevolutionPerSecond), RevolutionsPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - - var centiradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.CentiradianPerSecond); - AssertEx.EqualTolerance(CentiradiansPerSecondInOneRadianPerSecond, (double)centiradianpersecondQuantity.Value, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, centiradianpersecondQuantity.Unit); - - var deciradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DeciradianPerSecond); - AssertEx.EqualTolerance(DeciradiansPerSecondInOneRadianPerSecond, (double)deciradianpersecondQuantity.Value, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, deciradianpersecondQuantity.Unit); - - var degreeperminuteQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DegreePerMinute); - AssertEx.EqualTolerance(DegreesPerMinuteInOneRadianPerSecond, (double)degreeperminuteQuantity.Value, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, degreeperminuteQuantity.Unit); - - var degreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.DegreePerSecond); - AssertEx.EqualTolerance(DegreesPerSecondInOneRadianPerSecond, (double)degreepersecondQuantity.Value, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, degreepersecondQuantity.Unit); - - var microdegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MicrodegreePerSecond); - AssertEx.EqualTolerance(MicrodegreesPerSecondInOneRadianPerSecond, (double)microdegreepersecondQuantity.Value, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, microdegreepersecondQuantity.Unit); - - var microradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MicroradianPerSecond); - AssertEx.EqualTolerance(MicroradiansPerSecondInOneRadianPerSecond, (double)microradianpersecondQuantity.Value, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, microradianpersecondQuantity.Unit); - - var millidegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MillidegreePerSecond); - AssertEx.EqualTolerance(MillidegreesPerSecondInOneRadianPerSecond, (double)millidegreepersecondQuantity.Value, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, millidegreepersecondQuantity.Unit); - - var milliradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.MilliradianPerSecond); - AssertEx.EqualTolerance(MilliradiansPerSecondInOneRadianPerSecond, (double)milliradianpersecondQuantity.Value, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, milliradianpersecondQuantity.Unit); - - var nanodegreepersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.NanodegreePerSecond); - AssertEx.EqualTolerance(NanodegreesPerSecondInOneRadianPerSecond, (double)nanodegreepersecondQuantity.Value, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, nanodegreepersecondQuantity.Unit); - - var nanoradianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.NanoradianPerSecond); - AssertEx.EqualTolerance(NanoradiansPerSecondInOneRadianPerSecond, (double)nanoradianpersecondQuantity.Value, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, nanoradianpersecondQuantity.Unit); - - var radianpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RadianPerSecond); - AssertEx.EqualTolerance(RadiansPerSecondInOneRadianPerSecond, (double)radianpersecondQuantity.Value, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, radianpersecondQuantity.Unit); - - var revolutionperminuteQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RevolutionPerMinute); - AssertEx.EqualTolerance(RevolutionsPerMinuteInOneRadianPerSecond, (double)revolutionperminuteQuantity.Value, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, revolutionperminuteQuantity.Unit); - - var revolutionpersecondQuantity = radianpersecond.ToUnit(RotationalSpeedUnit.RevolutionPerSecond); - AssertEx.EqualTolerance(RevolutionsPerSecondInOneRadianPerSecond, (double)revolutionpersecondQuantity.Value, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, revolutionpersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(1, RotationalSpeed.FromCentiradiansPerSecond(radianpersecond.CentiradiansPerSecond).RadiansPerSecond, CentiradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDeciradiansPerSecond(radianpersecond.DeciradiansPerSecond).RadiansPerSecond, DeciradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDegreesPerMinute(radianpersecond.DegreesPerMinute).RadiansPerSecond, DegreesPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDegreesPerSecond(radianpersecond.DegreesPerSecond).RadiansPerSecond, DegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMicrodegreesPerSecond(radianpersecond.MicrodegreesPerSecond).RadiansPerSecond, MicrodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMicroradiansPerSecond(radianpersecond.MicroradiansPerSecond).RadiansPerSecond, MicroradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMillidegreesPerSecond(radianpersecond.MillidegreesPerSecond).RadiansPerSecond, MillidegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMilliradiansPerSecond(radianpersecond.MilliradiansPerSecond).RadiansPerSecond, MilliradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromNanodegreesPerSecond(radianpersecond.NanodegreesPerSecond).RadiansPerSecond, NanodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromNanoradiansPerSecond(radianpersecond.NanoradiansPerSecond).RadiansPerSecond, NanoradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRadiansPerSecond(radianpersecond.RadiansPerSecond).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRevolutionsPerMinute(radianpersecond.RevolutionsPerMinute).RadiansPerSecond, RevolutionsPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRevolutionsPerSecond(radianpersecond.RevolutionsPerSecond).RadiansPerSecond, RevolutionsPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - RotationalSpeed v = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(-1, -v.RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (RotationalSpeed.FromRadiansPerSecond(3)-v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (RotationalSpeed.FromRadiansPerSecond(10)/5).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, RotationalSpeed.FromRadiansPerSecond(10)/RotationalSpeed.FromRadiansPerSecond(5), RadiansPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - RotationalSpeed oneRadianPerSecond = RotationalSpeed.FromRadiansPerSecond(1); - RotationalSpeed twoRadiansPerSecond = RotationalSpeed.FromRadiansPerSecond(2); - - Assert.True(oneRadianPerSecond < twoRadiansPerSecond); - Assert.True(oneRadianPerSecond <= twoRadiansPerSecond); - Assert.True(twoRadiansPerSecond > oneRadianPerSecond); - Assert.True(twoRadiansPerSecond >= oneRadianPerSecond); - - Assert.False(oneRadianPerSecond > twoRadiansPerSecond); - Assert.False(oneRadianPerSecond >= twoRadiansPerSecond); - Assert.False(twoRadiansPerSecond < oneRadianPerSecond); - Assert.False(twoRadiansPerSecond <= oneRadianPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - Assert.Equal(0, radianpersecond.CompareTo(radianpersecond)); - Assert.True(radianpersecond.CompareTo(RotationalSpeed.Zero) > 0); - Assert.True(RotationalSpeed.Zero.CompareTo(radianpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - Assert.Throws(() => radianpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - Assert.Throws(() => radianpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - RotationalSpeed a = RotationalSpeed.FromRadiansPerSecond(1); - RotationalSpeed b = RotationalSpeed.FromRadiansPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - RotationalSpeed v = RotationalSpeed.FromRadiansPerSecond(1); - Assert.True(v.Equals(RotationalSpeed.FromRadiansPerSecond(1), RotationalSpeed.FromRadiansPerSecond(RadiansPerSecondTolerance))); - Assert.False(v.Equals(RotationalSpeed.Zero, RotationalSpeed.FromRadiansPerSecond(RadiansPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - Assert.False(radianpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - Assert.False(radianpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalSpeedUnit.Undefined, RotationalSpeed.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/RotationalStiffnessPerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/RotationalStiffnessPerLengthTestsBase.g.cs deleted file mode 100644 index 333b1b1c5d..0000000000 --- a/UnitsNet.Tests/GeneratedCode/RotationalStiffnessPerLengthTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of RotationalStiffnessPerLength. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class RotationalStiffnessPerLengthTestsBase - { - protected abstract double KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter { get; } - protected abstract double MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter { get; } - protected abstract double NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilonewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerRadianPerMeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonMeterPerRadianPerMeterToRotationalStiffnessPerLengthUnits() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter).KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter).MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - } - - [Fact] - public void As() - { - var newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter), KilonewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter), MeganewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, newtonmeterperradianpermeter.As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), NewtonMetersPerRadianPerMeterTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - - var kilonewtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)kilonewtonmeterperradianpermeterQuantity.Value, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, kilonewtonmeterperradianpermeterQuantity.Unit); - - var meganewtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)meganewtonmeterperradianpermeterQuantity.Value, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, meganewtonmeterperradianpermeterQuantity.Unit); - - var newtonmeterperradianpermeterQuantity = newtonmeterperradianpermeter.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(NewtonMetersPerRadianPerMeterInOneNewtonMeterPerRadianPerMeter, (double)newtonmeterperradianpermeterQuantity.Value, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, newtonmeterperradianpermeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.KilonewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.MeganewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.NewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - RotationalStiffnessPerLength v = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(3)-v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10)/5).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10)/RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(5), NewtonMetersPerRadianPerMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - RotationalStiffnessPerLength oneNewtonMeterPerRadianPerMeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - RotationalStiffnessPerLength twoNewtonMetersPerRadianPerMeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(2); - - Assert.True(oneNewtonMeterPerRadianPerMeter < twoNewtonMetersPerRadianPerMeter); - Assert.True(oneNewtonMeterPerRadianPerMeter <= twoNewtonMetersPerRadianPerMeter); - Assert.True(twoNewtonMetersPerRadianPerMeter > oneNewtonMeterPerRadianPerMeter); - Assert.True(twoNewtonMetersPerRadianPerMeter >= oneNewtonMeterPerRadianPerMeter); - - Assert.False(oneNewtonMeterPerRadianPerMeter > twoNewtonMetersPerRadianPerMeter); - Assert.False(oneNewtonMeterPerRadianPerMeter >= twoNewtonMetersPerRadianPerMeter); - Assert.False(twoNewtonMetersPerRadianPerMeter < oneNewtonMeterPerRadianPerMeter); - Assert.False(twoNewtonMetersPerRadianPerMeter <= oneNewtonMeterPerRadianPerMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.Equal(0, newtonmeterperradianpermeter.CompareTo(newtonmeterperradianpermeter)); - Assert.True(newtonmeterperradianpermeter.CompareTo(RotationalStiffnessPerLength.Zero) > 0); - Assert.True(RotationalStiffnessPerLength.Zero.CompareTo(newtonmeterperradianpermeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.Throws(() => newtonmeterperradianpermeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.Throws(() => newtonmeterperradianpermeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - RotationalStiffnessPerLength a = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - RotationalStiffnessPerLength b = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - RotationalStiffnessPerLength v = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.True(v.Equals(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1), RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(NewtonMetersPerRadianPerMeterTolerance))); - Assert.False(v.Equals(RotationalStiffnessPerLength.Zero, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(NewtonMetersPerRadianPerMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.False(newtonmeterperradianpermeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.False(newtonmeterperradianpermeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalStiffnessPerLengthUnit.Undefined, RotationalStiffnessPerLength.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/RotationalStiffnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/RotationalStiffnessTestsBase.g.cs deleted file mode 100644 index 0dba2bc6c5..0000000000 --- a/UnitsNet.Tests/GeneratedCode/RotationalStiffnessTestsBase.g.cs +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of RotationalStiffness. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class RotationalStiffnessTestsBase - { - protected abstract double KilonewtonMetersPerRadianInOneNewtonMeterPerRadian { get; } - protected abstract double MeganewtonMetersPerRadianInOneNewtonMeterPerRadian { get; } - protected abstract double NewtonMetersPerRadianInOneNewtonMeterPerRadian { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilonewtonMetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersPerRadianTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersPerRadianTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonMeterPerRadianToRotationalStiffnessUnits() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(NewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, RotationalStiffness.From(1, RotationalStiffnessUnit.KilonewtonMeterPerRadian).KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.From(1, RotationalStiffnessUnit.MeganewtonMeterPerRadian).MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.From(1, RotationalStiffnessUnit.NewtonMeterPerRadian).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - } - - [Fact] - public void As() - { - var newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.As(RotationalStiffnessUnit.KilonewtonMeterPerRadian), KilonewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.As(RotationalStiffnessUnit.MeganewtonMeterPerRadian), MeganewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(NewtonMetersPerRadianInOneNewtonMeterPerRadian, newtonmeterperradian.As(RotationalStiffnessUnit.NewtonMeterPerRadian), NewtonMetersPerRadianTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - - var kilonewtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerRadian); - AssertEx.EqualTolerance(KilonewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)kilonewtonmeterperradianQuantity.Value, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, kilonewtonmeterperradianQuantity.Unit); - - var meganewtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerRadian); - AssertEx.EqualTolerance(MeganewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)meganewtonmeterperradianQuantity.Value, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, meganewtonmeterperradianQuantity.Unit); - - var newtonmeterperradianQuantity = newtonmeterperradian.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian); - AssertEx.EqualTolerance(NewtonMetersPerRadianInOneNewtonMeterPerRadian, (double)newtonmeterperradianQuantity.Value, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, newtonmeterperradianQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilonewtonMetersPerRadian(newtonmeterperradian.KilonewtonMetersPerRadian).NewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMeganewtonMetersPerRadian(newtonmeterperradian.MeganewtonMetersPerRadian).NewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNewtonMetersPerRadian(newtonmeterperradian.NewtonMetersPerRadian).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - RotationalStiffness v = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(-1, -v.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffness.FromNewtonMetersPerRadian(3)-v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffness.FromNewtonMetersPerRadian(10)/5).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, RotationalStiffness.FromNewtonMetersPerRadian(10)/RotationalStiffness.FromNewtonMetersPerRadian(5), NewtonMetersPerRadianTolerance); - } - - [Fact] - public void ComparisonOperators() - { - RotationalStiffness oneNewtonMeterPerRadian = RotationalStiffness.FromNewtonMetersPerRadian(1); - RotationalStiffness twoNewtonMetersPerRadian = RotationalStiffness.FromNewtonMetersPerRadian(2); - - Assert.True(oneNewtonMeterPerRadian < twoNewtonMetersPerRadian); - Assert.True(oneNewtonMeterPerRadian <= twoNewtonMetersPerRadian); - Assert.True(twoNewtonMetersPerRadian > oneNewtonMeterPerRadian); - Assert.True(twoNewtonMetersPerRadian >= oneNewtonMeterPerRadian); - - Assert.False(oneNewtonMeterPerRadian > twoNewtonMetersPerRadian); - Assert.False(oneNewtonMeterPerRadian >= twoNewtonMetersPerRadian); - Assert.False(twoNewtonMetersPerRadian < oneNewtonMeterPerRadian); - Assert.False(twoNewtonMetersPerRadian <= oneNewtonMeterPerRadian); - } - - [Fact] - public void CompareToIsImplemented() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.Equal(0, newtonmeterperradian.CompareTo(newtonmeterperradian)); - Assert.True(newtonmeterperradian.CompareTo(RotationalStiffness.Zero) > 0); - Assert.True(RotationalStiffness.Zero.CompareTo(newtonmeterperradian) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.Throws(() => newtonmeterperradian.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.Throws(() => newtonmeterperradian.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - RotationalStiffness a = RotationalStiffness.FromNewtonMetersPerRadian(1); - RotationalStiffness b = RotationalStiffness.FromNewtonMetersPerRadian(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - RotationalStiffness v = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.True(v.Equals(RotationalStiffness.FromNewtonMetersPerRadian(1), RotationalStiffness.FromNewtonMetersPerRadian(NewtonMetersPerRadianTolerance))); - Assert.False(v.Equals(RotationalStiffness.Zero, RotationalStiffness.FromNewtonMetersPerRadian(NewtonMetersPerRadianTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.False(newtonmeterperradian.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.False(newtonmeterperradian.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalStiffnessUnit.Undefined, RotationalStiffness.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SolidAngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SolidAngleTestsBase.g.cs deleted file mode 100644 index 9a8ce58204..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SolidAngleTestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of SolidAngle. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SolidAngleTestsBase - { - protected abstract double SteradiansInOneSteradian { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double SteradiansTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SteradianToSolidAngleUnits() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(SteradiansInOneSteradian, steradian.Steradians, SteradiansTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, SolidAngle.From(1, SolidAngleUnit.Steradian).Steradians, SteradiansTolerance); - } - - [Fact] - public void As() - { - var steradian = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(SteradiansInOneSteradian, steradian.As(SolidAngleUnit.Steradian), SteradiansTolerance); - } - - [Fact] - public void ToUnit() - { - var steradian = SolidAngle.FromSteradians(1); - - var steradianQuantity = steradian.ToUnit(SolidAngleUnit.Steradian); - AssertEx.EqualTolerance(SteradiansInOneSteradian, (double)steradianQuantity.Value, SteradiansTolerance); - Assert.Equal(SolidAngleUnit.Steradian, steradianQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(1, SolidAngle.FromSteradians(steradian.Steradians).Steradians, SteradiansTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - SolidAngle v = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(-1, -v.Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (SolidAngle.FromSteradians(3)-v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (v + v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(10, (v*10).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(10, (10*v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (SolidAngle.FromSteradians(10)/5).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, SolidAngle.FromSteradians(10)/SolidAngle.FromSteradians(5), SteradiansTolerance); - } - - [Fact] - public void ComparisonOperators() - { - SolidAngle oneSteradian = SolidAngle.FromSteradians(1); - SolidAngle twoSteradians = SolidAngle.FromSteradians(2); - - Assert.True(oneSteradian < twoSteradians); - Assert.True(oneSteradian <= twoSteradians); - Assert.True(twoSteradians > oneSteradian); - Assert.True(twoSteradians >= oneSteradian); - - Assert.False(oneSteradian > twoSteradians); - Assert.False(oneSteradian >= twoSteradians); - Assert.False(twoSteradians < oneSteradian); - Assert.False(twoSteradians <= oneSteradian); - } - - [Fact] - public void CompareToIsImplemented() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.Equal(0, steradian.CompareTo(steradian)); - Assert.True(steradian.CompareTo(SolidAngle.Zero) > 0); - Assert.True(SolidAngle.Zero.CompareTo(steradian) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.Throws(() => steradian.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.Throws(() => steradian.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - SolidAngle a = SolidAngle.FromSteradians(1); - SolidAngle b = SolidAngle.FromSteradians(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - SolidAngle v = SolidAngle.FromSteradians(1); - Assert.True(v.Equals(SolidAngle.FromSteradians(1), SolidAngle.FromSteradians(SteradiansTolerance))); - Assert.False(v.Equals(SolidAngle.Zero, SolidAngle.FromSteradians(SteradiansTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.False(steradian.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.False(steradian.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SolidAngleUnit.Undefined, SolidAngle.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SpecificEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SpecificEnergyTestsBase.g.cs deleted file mode 100644 index 21f5e5a664..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SpecificEnergyTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of SpecificEnergy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SpecificEnergyTestsBase - { - protected abstract double CaloriesPerGramInOneJoulePerKilogram { get; } - protected abstract double JoulesPerKilogramInOneJoulePerKilogram { get; } - protected abstract double KilocaloriesPerGramInOneJoulePerKilogram { get; } - protected abstract double KilojoulesPerKilogramInOneJoulePerKilogram { get; } - protected abstract double KilowattHoursPerKilogramInOneJoulePerKilogram { get; } - protected abstract double MegajoulesPerKilogramInOneJoulePerKilogram { get; } - protected abstract double MegawattHoursPerKilogramInOneJoulePerKilogram { get; } - protected abstract double WattHoursPerKilogramInOneJoulePerKilogram { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CaloriesPerGramTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerGramTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double KilowattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramTolerance { get { return 1e-5; } } - protected virtual double MegawattHoursPerKilogramTolerance { get { return 1e-5; } } - protected virtual double WattHoursPerKilogramTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerKilogramToSpecificEnergyUnits() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(CaloriesPerGramInOneJoulePerKilogram, jouleperkilogram.CaloriesPerGram, CaloriesPerGramTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(KilocaloriesPerGramInOneJoulePerKilogram, jouleperkilogram.KilocaloriesPerGram, KilocaloriesPerGramTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.KilojoulesPerKilogram, KilojoulesPerKilogramTolerance); - AssertEx.EqualTolerance(KilowattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.KilowattHoursPerKilogram, KilowattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.MegajoulesPerKilogram, MegajoulesPerKilogramTolerance); - AssertEx.EqualTolerance(MegawattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.MegawattHoursPerKilogram, MegawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(WattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.WattHoursPerKilogram, WattHoursPerKilogramTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.CaloriePerGram).CaloriesPerGram, CaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.JoulePerKilogram).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.KilocaloriePerGram).KilocaloriesPerGram, KilocaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.KilojoulePerKilogram).KilojoulesPerKilogram, KilojoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.KilowattHourPerKilogram).KilowattHoursPerKilogram, KilowattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.MegajoulePerKilogram).MegajoulesPerKilogram, MegajoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.MegawattHourPerKilogram).MegawattHoursPerKilogram, MegawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.From(1, SpecificEnergyUnit.WattHourPerKilogram).WattHoursPerKilogram, WattHoursPerKilogramTolerance); - } - - [Fact] - public void As() - { - var jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(CaloriesPerGramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.CaloriePerGram), CaloriesPerGramTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.JoulePerKilogram), JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(KilocaloriesPerGramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.KilocaloriePerGram), KilocaloriesPerGramTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.KilojoulePerKilogram), KilojoulesPerKilogramTolerance); - AssertEx.EqualTolerance(KilowattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.KilowattHourPerKilogram), KilowattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.MegajoulePerKilogram), MegajoulesPerKilogramTolerance); - AssertEx.EqualTolerance(MegawattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.MegawattHourPerKilogram), MegawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(WattHoursPerKilogramInOneJoulePerKilogram, jouleperkilogram.As(SpecificEnergyUnit.WattHourPerKilogram), WattHoursPerKilogramTolerance); - } - - [Fact] - public void ToUnit() - { - var jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - - var caloriepergramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.CaloriePerGram); - AssertEx.EqualTolerance(CaloriesPerGramInOneJoulePerKilogram, (double)caloriepergramQuantity.Value, CaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.CaloriePerGram, caloriepergramQuantity.Unit); - - var jouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.JoulePerKilogram); - AssertEx.EqualTolerance(JoulesPerKilogramInOneJoulePerKilogram, (double)jouleperkilogramQuantity.Value, JoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, jouleperkilogramQuantity.Unit); - - var kilocaloriepergramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilocaloriePerGram); - AssertEx.EqualTolerance(KilocaloriesPerGramInOneJoulePerKilogram, (double)kilocaloriepergramQuantity.Value, KilocaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.KilocaloriePerGram, kilocaloriepergramQuantity.Unit); - - var kilojouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilojoulePerKilogram); - AssertEx.EqualTolerance(KilojoulesPerKilogramInOneJoulePerKilogram, (double)kilojouleperkilogramQuantity.Value, KilojoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilojoulePerKilogram, kilojouleperkilogramQuantity.Unit); - - var kilowatthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.KilowattHourPerKilogram); - AssertEx.EqualTolerance(KilowattHoursPerKilogramInOneJoulePerKilogram, (double)kilowatthourperkilogramQuantity.Value, KilowattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerKilogram, kilowatthourperkilogramQuantity.Unit); - - var megajouleperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegajoulePerKilogram); - AssertEx.EqualTolerance(MegajoulesPerKilogramInOneJoulePerKilogram, (double)megajouleperkilogramQuantity.Value, MegajoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegajoulePerKilogram, megajouleperkilogramQuantity.Unit); - - var megawatthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.MegawattHourPerKilogram); - AssertEx.EqualTolerance(MegawattHoursPerKilogramInOneJoulePerKilogram, (double)megawatthourperkilogramQuantity.Value, MegawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerKilogram, megawatthourperkilogramQuantity.Unit); - - var watthourperkilogramQuantity = jouleperkilogram.ToUnit(SpecificEnergyUnit.WattHourPerKilogram); - AssertEx.EqualTolerance(WattHoursPerKilogramInOneJoulePerKilogram, (double)watthourperkilogramQuantity.Value, WattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerKilogram, watthourperkilogramQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(1, SpecificEnergy.FromCaloriesPerGram(jouleperkilogram.CaloriesPerGram).JoulesPerKilogram, CaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromJoulesPerKilogram(jouleperkilogram.JoulesPerKilogram).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilocaloriesPerGram(jouleperkilogram.KilocaloriesPerGram).JoulesPerKilogram, KilocaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilojoulesPerKilogram(jouleperkilogram.KilojoulesPerKilogram).JoulesPerKilogram, KilojoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattHoursPerKilogram(jouleperkilogram.KilowattHoursPerKilogram).JoulesPerKilogram, KilowattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegajoulesPerKilogram(jouleperkilogram.MegajoulesPerKilogram).JoulesPerKilogram, MegajoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattHoursPerKilogram(jouleperkilogram.MegawattHoursPerKilogram).JoulesPerKilogram, MegawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattHoursPerKilogram(jouleperkilogram.WattHoursPerKilogram).JoulesPerKilogram, WattHoursPerKilogramTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - SpecificEnergy v = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificEnergy.FromJoulesPerKilogram(3)-v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificEnergy.FromJoulesPerKilogram(10)/5).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, SpecificEnergy.FromJoulesPerKilogram(10)/SpecificEnergy.FromJoulesPerKilogram(5), JoulesPerKilogramTolerance); - } - - [Fact] - public void ComparisonOperators() - { - SpecificEnergy oneJoulePerKilogram = SpecificEnergy.FromJoulesPerKilogram(1); - SpecificEnergy twoJoulesPerKilogram = SpecificEnergy.FromJoulesPerKilogram(2); - - Assert.True(oneJoulePerKilogram < twoJoulesPerKilogram); - Assert.True(oneJoulePerKilogram <= twoJoulesPerKilogram); - Assert.True(twoJoulesPerKilogram > oneJoulePerKilogram); - Assert.True(twoJoulesPerKilogram >= oneJoulePerKilogram); - - Assert.False(oneJoulePerKilogram > twoJoulesPerKilogram); - Assert.False(oneJoulePerKilogram >= twoJoulesPerKilogram); - Assert.False(twoJoulesPerKilogram < oneJoulePerKilogram); - Assert.False(twoJoulesPerKilogram <= oneJoulePerKilogram); - } - - [Fact] - public void CompareToIsImplemented() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.Equal(0, jouleperkilogram.CompareTo(jouleperkilogram)); - Assert.True(jouleperkilogram.CompareTo(SpecificEnergy.Zero) > 0); - Assert.True(SpecificEnergy.Zero.CompareTo(jouleperkilogram) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.Throws(() => jouleperkilogram.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.Throws(() => jouleperkilogram.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - SpecificEnergy a = SpecificEnergy.FromJoulesPerKilogram(1); - SpecificEnergy b = SpecificEnergy.FromJoulesPerKilogram(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - SpecificEnergy v = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.True(v.Equals(SpecificEnergy.FromJoulesPerKilogram(1), SpecificEnergy.FromJoulesPerKilogram(JoulesPerKilogramTolerance))); - Assert.False(v.Equals(SpecificEnergy.Zero, SpecificEnergy.FromJoulesPerKilogram(JoulesPerKilogramTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.False(jouleperkilogram.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.False(jouleperkilogram.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificEnergyUnit.Undefined, SpecificEnergy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SpecificEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SpecificEntropyTestsBase.g.cs deleted file mode 100644 index 484e9ad12b..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SpecificEntropyTestsBase.g.cs +++ /dev/null @@ -1,267 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of SpecificEntropy. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SpecificEntropyTestsBase - { - protected abstract double CaloriesPerGramKelvinInOneJoulePerKilogramKelvin { get; } - protected abstract double JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin { get; } - protected abstract double JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin { get; } - protected abstract double KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin { get; } - protected abstract double KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin { get; } - protected abstract double KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin { get; } - protected abstract double MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin { get; } - protected abstract double MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CaloriesPerGramKelvinTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double JoulesPerKilogramKelvinTolerance { get { return 1e-5; } } - protected virtual double KilocaloriesPerGramKelvinTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerKilogramKelvinTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramDegreeCelsiusTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerKilogramKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void JoulePerKilogramKelvinToSpecificEntropyUnits() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(CaloriesPerGramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.CaloriesPerGramKelvin, CaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.JoulesPerKilogramDegreeCelsius, JoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.KilocaloriesPerGramKelvin, KilocaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.KilojoulesPerKilogramDegreeCelsius, KilojoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.KilojoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.MegajoulesPerKilogramDegreeCelsius, MegajoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.MegajoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.CaloriePerGramKelvin).CaloriesPerGramKelvin, CaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius).JoulesPerKilogramDegreeCelsius, JoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.JoulePerKilogramKelvin).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.KilocaloriePerGramKelvin).KilocaloriesPerGramKelvin, KilocaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius).KilojoulesPerKilogramDegreeCelsius, KilojoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.KilojoulePerKilogramKelvin).KilojoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius).MegajoulesPerKilogramDegreeCelsius, MegajoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.From(1, SpecificEntropyUnit.MegajoulePerKilogramKelvin).MegajoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); - } - - [Fact] - public void As() - { - var jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(CaloriesPerGramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.CaloriePerGramKelvin), CaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius), JoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.JoulePerKilogramKelvin), JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.KilocaloriePerGramKelvin), KilocaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius), KilojoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.KilojoulePerKilogramKelvin), KilojoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius), MegajoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, jouleperkilogramkelvin.As(SpecificEntropyUnit.MegajoulePerKilogramKelvin), MegajoulesPerKilogramKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - - var caloriepergramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.CaloriePerGramKelvin); - AssertEx.EqualTolerance(CaloriesPerGramKelvinInOneJoulePerKilogramKelvin, (double)caloriepergramkelvinQuantity.Value, CaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.CaloriePerGramKelvin, caloriepergramkelvinQuantity.Unit); - - var jouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(JoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)jouleperkilogramdegreecelsiusQuantity.Value, JoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, jouleperkilogramdegreecelsiusQuantity.Unit); - - var jouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin); - AssertEx.EqualTolerance(JoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)jouleperkilogramkelvinQuantity.Value, JoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, jouleperkilogramkelvinQuantity.Unit); - - var kilocaloriepergramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilocaloriePerGramKelvin); - AssertEx.EqualTolerance(KilocaloriesPerGramKelvinInOneJoulePerKilogramKelvin, (double)kilocaloriepergramkelvinQuantity.Value, KilocaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilocaloriePerGramKelvin, kilocaloriepergramkelvinQuantity.Unit); - - var kilojouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(KilojoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)kilojouleperkilogramdegreecelsiusQuantity.Value, KilojoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, kilojouleperkilogramdegreecelsiusQuantity.Unit); - - var kilojouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramKelvin); - AssertEx.EqualTolerance(KilojoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)kilojouleperkilogramkelvinQuantity.Value, KilojoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramKelvin, kilojouleperkilogramkelvinQuantity.Unit); - - var megajouleperkilogramdegreecelsiusQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(MegajoulesPerKilogramDegreeCelsiusInOneJoulePerKilogramKelvin, (double)megajouleperkilogramdegreecelsiusQuantity.Value, MegajoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, megajouleperkilogramdegreecelsiusQuantity.Unit); - - var megajouleperkilogramkelvinQuantity = jouleperkilogramkelvin.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramKelvin); - AssertEx.EqualTolerance(MegajoulesPerKilogramKelvinInOneJoulePerKilogramKelvin, (double)megajouleperkilogramkelvinQuantity.Value, MegajoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramKelvin, megajouleperkilogramkelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(1, SpecificEntropy.FromCaloriesPerGramKelvin(jouleperkilogramkelvin.CaloriesPerGramKelvin).JoulesPerKilogramKelvin, CaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.JoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, JoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromJoulesPerKilogramKelvin(jouleperkilogramkelvin.JoulesPerKilogramKelvin).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilocaloriesPerGramKelvin(jouleperkilogramkelvin.KilocaloriesPerGramKelvin).JoulesPerKilogramKelvin, KilocaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.KilojoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, KilojoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilojoulesPerKilogramKelvin(jouleperkilogramkelvin.KilojoulesPerKilogramKelvin).JoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.MegajoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, MegajoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromMegajoulesPerKilogramKelvin(jouleperkilogramkelvin.MegajoulesPerKilogramKelvin).JoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - SpecificEntropy v = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(3)-v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(10)/5).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, SpecificEntropy.FromJoulesPerKilogramKelvin(10)/SpecificEntropy.FromJoulesPerKilogramKelvin(5), JoulesPerKilogramKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - SpecificEntropy oneJoulePerKilogramKelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - SpecificEntropy twoJoulesPerKilogramKelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(2); - - Assert.True(oneJoulePerKilogramKelvin < twoJoulesPerKilogramKelvin); - Assert.True(oneJoulePerKilogramKelvin <= twoJoulesPerKilogramKelvin); - Assert.True(twoJoulesPerKilogramKelvin > oneJoulePerKilogramKelvin); - Assert.True(twoJoulesPerKilogramKelvin >= oneJoulePerKilogramKelvin); - - Assert.False(oneJoulePerKilogramKelvin > twoJoulesPerKilogramKelvin); - Assert.False(oneJoulePerKilogramKelvin >= twoJoulesPerKilogramKelvin); - Assert.False(twoJoulesPerKilogramKelvin < oneJoulePerKilogramKelvin); - Assert.False(twoJoulesPerKilogramKelvin <= oneJoulePerKilogramKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.Equal(0, jouleperkilogramkelvin.CompareTo(jouleperkilogramkelvin)); - Assert.True(jouleperkilogramkelvin.CompareTo(SpecificEntropy.Zero) > 0); - Assert.True(SpecificEntropy.Zero.CompareTo(jouleperkilogramkelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.Throws(() => jouleperkilogramkelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.Throws(() => jouleperkilogramkelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - SpecificEntropy a = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - SpecificEntropy b = SpecificEntropy.FromJoulesPerKilogramKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - SpecificEntropy v = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.True(v.Equals(SpecificEntropy.FromJoulesPerKilogramKelvin(1), SpecificEntropy.FromJoulesPerKilogramKelvin(JoulesPerKilogramKelvinTolerance))); - Assert.False(v.Equals(SpecificEntropy.Zero, SpecificEntropy.FromJoulesPerKilogramKelvin(JoulesPerKilogramKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.False(jouleperkilogramkelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.False(jouleperkilogramkelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificEntropyUnit.Undefined, SpecificEntropy.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SpecificVolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SpecificVolumeTestsBase.g.cs deleted file mode 100644 index 8ad46ec812..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SpecificVolumeTestsBase.g.cs +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of SpecificVolume. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SpecificVolumeTestsBase - { - protected abstract double CubicFeetPerPoundInOneCubicMeterPerKilogram { get; } - protected abstract double CubicMetersPerKilogramInOneCubicMeterPerKilogram { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CubicFeetPerPoundTolerance { get { return 1e-5; } } - protected virtual double CubicMetersPerKilogramTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CubicMeterPerKilogramToSpecificVolumeUnits() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(CubicFeetPerPoundInOneCubicMeterPerKilogram, cubicmeterperkilogram.CubicFeetPerPound, CubicFeetPerPoundTolerance); - AssertEx.EqualTolerance(CubicMetersPerKilogramInOneCubicMeterPerKilogram, cubicmeterperkilogram.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, SpecificVolume.From(1, SpecificVolumeUnit.CubicFootPerPound).CubicFeetPerPound, CubicFeetPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificVolume.From(1, SpecificVolumeUnit.CubicMeterPerKilogram).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - } - - [Fact] - public void As() - { - var cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(CubicFeetPerPoundInOneCubicMeterPerKilogram, cubicmeterperkilogram.As(SpecificVolumeUnit.CubicFootPerPound), CubicFeetPerPoundTolerance); - AssertEx.EqualTolerance(CubicMetersPerKilogramInOneCubicMeterPerKilogram, cubicmeterperkilogram.As(SpecificVolumeUnit.CubicMeterPerKilogram), CubicMetersPerKilogramTolerance); - } - - [Fact] - public void ToUnit() - { - var cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - - var cubicfootperpoundQuantity = cubicmeterperkilogram.ToUnit(SpecificVolumeUnit.CubicFootPerPound); - AssertEx.EqualTolerance(CubicFeetPerPoundInOneCubicMeterPerKilogram, (double)cubicfootperpoundQuantity.Value, CubicFeetPerPoundTolerance); - Assert.Equal(SpecificVolumeUnit.CubicFootPerPound, cubicfootperpoundQuantity.Unit); - - var cubicmeterperkilogramQuantity = cubicmeterperkilogram.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram); - AssertEx.EqualTolerance(CubicMetersPerKilogramInOneCubicMeterPerKilogram, (double)cubicmeterperkilogramQuantity.Value, CubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, cubicmeterperkilogramQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(1, SpecificVolume.FromCubicFeetPerPound(cubicmeterperkilogram.CubicFeetPerPound).CubicMetersPerKilogram, CubicFeetPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificVolume.FromCubicMetersPerKilogram(cubicmeterperkilogram.CubicMetersPerKilogram).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - SpecificVolume v = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificVolume.FromCubicMetersPerKilogram(3)-v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificVolume.FromCubicMetersPerKilogram(10)/5).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, SpecificVolume.FromCubicMetersPerKilogram(10)/SpecificVolume.FromCubicMetersPerKilogram(5), CubicMetersPerKilogramTolerance); - } - - [Fact] - public void ComparisonOperators() - { - SpecificVolume oneCubicMeterPerKilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - SpecificVolume twoCubicMetersPerKilogram = SpecificVolume.FromCubicMetersPerKilogram(2); - - Assert.True(oneCubicMeterPerKilogram < twoCubicMetersPerKilogram); - Assert.True(oneCubicMeterPerKilogram <= twoCubicMetersPerKilogram); - Assert.True(twoCubicMetersPerKilogram > oneCubicMeterPerKilogram); - Assert.True(twoCubicMetersPerKilogram >= oneCubicMeterPerKilogram); - - Assert.False(oneCubicMeterPerKilogram > twoCubicMetersPerKilogram); - Assert.False(oneCubicMeterPerKilogram >= twoCubicMetersPerKilogram); - Assert.False(twoCubicMetersPerKilogram < oneCubicMeterPerKilogram); - Assert.False(twoCubicMetersPerKilogram <= oneCubicMeterPerKilogram); - } - - [Fact] - public void CompareToIsImplemented() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.Equal(0, cubicmeterperkilogram.CompareTo(cubicmeterperkilogram)); - Assert.True(cubicmeterperkilogram.CompareTo(SpecificVolume.Zero) > 0); - Assert.True(SpecificVolume.Zero.CompareTo(cubicmeterperkilogram) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.Throws(() => cubicmeterperkilogram.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.Throws(() => cubicmeterperkilogram.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - SpecificVolume a = SpecificVolume.FromCubicMetersPerKilogram(1); - SpecificVolume b = SpecificVolume.FromCubicMetersPerKilogram(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - SpecificVolume v = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.True(v.Equals(SpecificVolume.FromCubicMetersPerKilogram(1), SpecificVolume.FromCubicMetersPerKilogram(CubicMetersPerKilogramTolerance))); - Assert.False(v.Equals(SpecificVolume.Zero, SpecificVolume.FromCubicMetersPerKilogram(CubicMetersPerKilogramTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.False(cubicmeterperkilogram.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.False(cubicmeterperkilogram.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificVolumeUnit.Undefined, SpecificVolume.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SpecificWeightTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SpecificWeightTestsBase.g.cs deleted file mode 100644 index 6ce9860bf4..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SpecificWeightTestsBase.g.cs +++ /dev/null @@ -1,357 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of SpecificWeight. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SpecificWeightTestsBase - { - protected abstract double KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter { get; } - protected abstract double KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter { get; } - protected abstract double KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter { get; } - protected abstract double MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter { get; } - protected abstract double NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter { get; } - protected abstract double NewtonsPerCubicMeterInOneNewtonPerCubicMeter { get; } - protected abstract double NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter { get; } - protected abstract double PoundsForcePerCubicFootInOneNewtonPerCubicMeter { get; } - protected abstract double PoundsForcePerCubicInchInOneNewtonPerCubicMeter { get; } - protected abstract double TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter { get; } - protected abstract double TonnesForcePerCubicMeterInOneNewtonPerCubicMeter { get; } - protected abstract double TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramsForcePerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilogramsForcePerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double KilonewtonsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerCubicFootTolerance { get { return 1e-5; } } - protected virtual double KilopoundsForcePerCubicInchTolerance { get { return 1e-5; } } - protected virtual double MeganewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double NewtonsPerCubicMillimeterTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerCubicFootTolerance { get { return 1e-5; } } - protected virtual double PoundsForcePerCubicInchTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicCentimeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicMeterTolerance { get { return 1e-5; } } - protected virtual double TonnesForcePerCubicMillimeterTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonPerCubicMeterToSpecificWeightUnits() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilogramsForcePerCubicCentimeter, KilogramsForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilogramsForcePerCubicMeter, KilogramsForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilogramsForcePerCubicMillimeter, KilogramsForcePerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilonewtonsPerCubicCentimeter, KilonewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilonewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.KilonewtonsPerCubicMillimeter, KilonewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter, newtonpercubicmeter.KilopoundsForcePerCubicFoot, KilopoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter, newtonpercubicmeter.KilopoundsForcePerCubicInch, KilopoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.MeganewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.NewtonsPerCubicCentimeter, NewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.NewtonsPerCubicMillimeter, NewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(PoundsForcePerCubicFootInOneNewtonPerCubicMeter, newtonpercubicmeter.PoundsForcePerCubicFoot, PoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(PoundsForcePerCubicInchInOneNewtonPerCubicMeter, newtonpercubicmeter.PoundsForcePerCubicInch, PoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.TonnesForcePerCubicCentimeter, TonnesForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.TonnesForcePerCubicMeter, TonnesForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.TonnesForcePerCubicMillimeter, TonnesForcePerCubicMillimeterTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicCentimeter).KilogramsForcePerCubicCentimeter, KilogramsForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicMeter).KilogramsForcePerCubicMeter, KilogramsForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicMillimeter).KilogramsForcePerCubicMillimeter, KilogramsForcePerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicCentimeter).KilonewtonsPerCubicCentimeter, KilonewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicMeter).KilonewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicMillimeter).KilonewtonsPerCubicMillimeter, KilonewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilopoundForcePerCubicFoot).KilopoundsForcePerCubicFoot, KilopoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.KilopoundForcePerCubicInch).KilopoundsForcePerCubicInch, KilopoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.MeganewtonPerCubicMeter).MeganewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicCentimeter).NewtonsPerCubicCentimeter, NewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicMeter).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicMillimeter).NewtonsPerCubicMillimeter, NewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.PoundForcePerCubicFoot).PoundsForcePerCubicFoot, PoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.PoundForcePerCubicInch).PoundsForcePerCubicInch, PoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicCentimeter).TonnesForcePerCubicCentimeter, TonnesForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicMeter).TonnesForcePerCubicMeter, TonnesForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicMillimeter).TonnesForcePerCubicMillimeter, TonnesForcePerCubicMillimeterTolerance); - } - - [Fact] - public void As() - { - var newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilogramForcePerCubicCentimeter), KilogramsForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilogramForcePerCubicMeter), KilogramsForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilogramForcePerCubicMillimeter), KilogramsForcePerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilonewtonPerCubicCentimeter), KilonewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilonewtonPerCubicMeter), KilonewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilonewtonPerCubicMillimeter), KilonewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilopoundForcePerCubicFoot), KilopoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.KilopoundForcePerCubicInch), KilopoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.MeganewtonPerCubicMeter), MeganewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.NewtonPerCubicCentimeter), NewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.NewtonPerCubicMeter), NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.NewtonPerCubicMillimeter), NewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(PoundsForcePerCubicFootInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.PoundForcePerCubicFoot), PoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(PoundsForcePerCubicInchInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.PoundForcePerCubicInch), PoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.TonneForcePerCubicCentimeter), TonnesForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicMeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.TonneForcePerCubicMeter), TonnesForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter, newtonpercubicmeter.As(SpecificWeightUnit.TonneForcePerCubicMillimeter), TonnesForcePerCubicMillimeterTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - - var kilogramforcepercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicCentimeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicCentimeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubiccentimeterQuantity.Value, KilogramsForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicCentimeter, kilogramforcepercubiccentimeterQuantity.Unit); - - var kilogramforcepercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicMeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubicmeterQuantity.Value, KilogramsForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMeter, kilogramforcepercubicmeterQuantity.Unit); - - var kilogramforcepercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMillimeter); - AssertEx.EqualTolerance(KilogramsForcePerCubicMillimeterInOneNewtonPerCubicMeter, (double)kilogramforcepercubicmillimeterQuantity.Value, KilogramsForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMillimeter, kilogramforcepercubicmillimeterQuantity.Unit); - - var kilonewtonpercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicCentimeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubiccentimeterQuantity.Value, KilonewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicCentimeter, kilonewtonpercubiccentimeterQuantity.Unit); - - var kilonewtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubicmeterQuantity.Value, KilonewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMeter, kilonewtonpercubicmeterQuantity.Unit); - - var kilonewtonpercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMillimeter); - AssertEx.EqualTolerance(KilonewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, (double)kilonewtonpercubicmillimeterQuantity.Value, KilonewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMillimeter, kilonewtonpercubicmillimeterQuantity.Unit); - - var kilopoundforcepercubicfootQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicFoot); - AssertEx.EqualTolerance(KilopoundsForcePerCubicFootInOneNewtonPerCubicMeter, (double)kilopoundforcepercubicfootQuantity.Value, KilopoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicFoot, kilopoundforcepercubicfootQuantity.Unit); - - var kilopoundforcepercubicinchQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicInch); - AssertEx.EqualTolerance(KilopoundsForcePerCubicInchInOneNewtonPerCubicMeter, (double)kilopoundforcepercubicinchQuantity.Value, KilopoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicInch, kilopoundforcepercubicinchQuantity.Unit); - - var meganewtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.MeganewtonPerCubicMeter); - AssertEx.EqualTolerance(MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)meganewtonpercubicmeterQuantity.Value, MeganewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.MeganewtonPerCubicMeter, meganewtonpercubicmeterQuantity.Unit); - - var newtonpercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicCentimeter); - AssertEx.EqualTolerance(NewtonsPerCubicCentimeterInOneNewtonPerCubicMeter, (double)newtonpercubiccentimeterQuantity.Value, NewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicCentimeter, newtonpercubiccentimeterQuantity.Unit); - - var newtonpercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter); - AssertEx.EqualTolerance(NewtonsPerCubicMeterInOneNewtonPerCubicMeter, (double)newtonpercubicmeterQuantity.Value, NewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, newtonpercubicmeterQuantity.Unit); - - var newtonpercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.NewtonPerCubicMillimeter); - AssertEx.EqualTolerance(NewtonsPerCubicMillimeterInOneNewtonPerCubicMeter, (double)newtonpercubicmillimeterQuantity.Value, NewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMillimeter, newtonpercubicmillimeterQuantity.Unit); - - var poundforcepercubicfootQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.PoundForcePerCubicFoot); - AssertEx.EqualTolerance(PoundsForcePerCubicFootInOneNewtonPerCubicMeter, (double)poundforcepercubicfootQuantity.Value, PoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicFoot, poundforcepercubicfootQuantity.Unit); - - var poundforcepercubicinchQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.PoundForcePerCubicInch); - AssertEx.EqualTolerance(PoundsForcePerCubicInchInOneNewtonPerCubicMeter, (double)poundforcepercubicinchQuantity.Value, PoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicInch, poundforcepercubicinchQuantity.Unit); - - var tonneforcepercubiccentimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicCentimeter); - AssertEx.EqualTolerance(TonnesForcePerCubicCentimeterInOneNewtonPerCubicMeter, (double)tonneforcepercubiccentimeterQuantity.Value, TonnesForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicCentimeter, tonneforcepercubiccentimeterQuantity.Unit); - - var tonneforcepercubicmeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicMeter); - AssertEx.EqualTolerance(TonnesForcePerCubicMeterInOneNewtonPerCubicMeter, (double)tonneforcepercubicmeterQuantity.Value, TonnesForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMeter, tonneforcepercubicmeterQuantity.Unit); - - var tonneforcepercubicmillimeterQuantity = newtonpercubicmeter.ToUnit(SpecificWeightUnit.TonneForcePerCubicMillimeter); - AssertEx.EqualTolerance(TonnesForcePerCubicMillimeterInOneNewtonPerCubicMeter, (double)tonneforcepercubicmillimeterQuantity.Value, TonnesForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMillimeter, tonneforcepercubicmillimeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicCentimeter(newtonpercubicmeter.KilogramsForcePerCubicCentimeter).NewtonsPerCubicMeter, KilogramsForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicMeter(newtonpercubicmeter.KilogramsForcePerCubicMeter).NewtonsPerCubicMeter, KilogramsForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicMillimeter(newtonpercubicmeter.KilogramsForcePerCubicMillimeter).NewtonsPerCubicMeter, KilogramsForcePerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicCentimeter(newtonpercubicmeter.KilonewtonsPerCubicCentimeter).NewtonsPerCubicMeter, KilonewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicMeter(newtonpercubicmeter.KilonewtonsPerCubicMeter).NewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicMillimeter(newtonpercubicmeter.KilonewtonsPerCubicMillimeter).NewtonsPerCubicMeter, KilonewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilopoundsForcePerCubicFoot(newtonpercubicmeter.KilopoundsForcePerCubicFoot).NewtonsPerCubicMeter, KilopoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilopoundsForcePerCubicInch(newtonpercubicmeter.KilopoundsForcePerCubicInch).NewtonsPerCubicMeter, KilopoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromMeganewtonsPerCubicMeter(newtonpercubicmeter.MeganewtonsPerCubicMeter).NewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicCentimeter(newtonpercubicmeter.NewtonsPerCubicCentimeter).NewtonsPerCubicMeter, NewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicMeter(newtonpercubicmeter.NewtonsPerCubicMeter).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicMillimeter(newtonpercubicmeter.NewtonsPerCubicMillimeter).NewtonsPerCubicMeter, NewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromPoundsForcePerCubicFoot(newtonpercubicmeter.PoundsForcePerCubicFoot).NewtonsPerCubicMeter, PoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromPoundsForcePerCubicInch(newtonpercubicmeter.PoundsForcePerCubicInch).NewtonsPerCubicMeter, PoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicCentimeter(newtonpercubicmeter.TonnesForcePerCubicCentimeter).NewtonsPerCubicMeter, TonnesForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicMeter(newtonpercubicmeter.TonnesForcePerCubicMeter).NewtonsPerCubicMeter, TonnesForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicMillimeter(newtonpercubicmeter.TonnesForcePerCubicMillimeter).NewtonsPerCubicMeter, TonnesForcePerCubicMillimeterTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - SpecificWeight v = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (SpecificWeight.FromNewtonsPerCubicMeter(3)-v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (SpecificWeight.FromNewtonsPerCubicMeter(10)/5).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, SpecificWeight.FromNewtonsPerCubicMeter(10)/SpecificWeight.FromNewtonsPerCubicMeter(5), NewtonsPerCubicMeterTolerance); - } - - [Fact] - public void ComparisonOperators() - { - SpecificWeight oneNewtonPerCubicMeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - SpecificWeight twoNewtonsPerCubicMeter = SpecificWeight.FromNewtonsPerCubicMeter(2); - - Assert.True(oneNewtonPerCubicMeter < twoNewtonsPerCubicMeter); - Assert.True(oneNewtonPerCubicMeter <= twoNewtonsPerCubicMeter); - Assert.True(twoNewtonsPerCubicMeter > oneNewtonPerCubicMeter); - Assert.True(twoNewtonsPerCubicMeter >= oneNewtonPerCubicMeter); - - Assert.False(oneNewtonPerCubicMeter > twoNewtonsPerCubicMeter); - Assert.False(oneNewtonPerCubicMeter >= twoNewtonsPerCubicMeter); - Assert.False(twoNewtonsPerCubicMeter < oneNewtonPerCubicMeter); - Assert.False(twoNewtonsPerCubicMeter <= oneNewtonPerCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.Equal(0, newtonpercubicmeter.CompareTo(newtonpercubicmeter)); - Assert.True(newtonpercubicmeter.CompareTo(SpecificWeight.Zero) > 0); - Assert.True(SpecificWeight.Zero.CompareTo(newtonpercubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.Throws(() => newtonpercubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.Throws(() => newtonpercubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - SpecificWeight a = SpecificWeight.FromNewtonsPerCubicMeter(1); - SpecificWeight b = SpecificWeight.FromNewtonsPerCubicMeter(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - SpecificWeight v = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.True(v.Equals(SpecificWeight.FromNewtonsPerCubicMeter(1), SpecificWeight.FromNewtonsPerCubicMeter(NewtonsPerCubicMeterTolerance))); - Assert.False(v.Equals(SpecificWeight.Zero, SpecificWeight.FromNewtonsPerCubicMeter(NewtonsPerCubicMeterTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.False(newtonpercubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.False(newtonpercubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificWeightUnit.Undefined, SpecificWeight.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/SpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/SpeedTestsBase.g.cs deleted file mode 100644 index 44c1e91ab3..0000000000 --- a/UnitsNet.Tests/GeneratedCode/SpeedTestsBase.g.cs +++ /dev/null @@ -1,507 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Speed. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class SpeedTestsBase - { - protected abstract double CentimetersPerHourInOneMeterPerSecond { get; } - protected abstract double CentimetersPerMinutesInOneMeterPerSecond { get; } - protected abstract double CentimetersPerSecondInOneMeterPerSecond { get; } - protected abstract double DecimetersPerMinutesInOneMeterPerSecond { get; } - protected abstract double DecimetersPerSecondInOneMeterPerSecond { get; } - protected abstract double FeetPerHourInOneMeterPerSecond { get; } - protected abstract double FeetPerMinuteInOneMeterPerSecond { get; } - protected abstract double FeetPerSecondInOneMeterPerSecond { get; } - protected abstract double InchesPerHourInOneMeterPerSecond { get; } - protected abstract double InchesPerMinuteInOneMeterPerSecond { get; } - protected abstract double InchesPerSecondInOneMeterPerSecond { get; } - protected abstract double KilometersPerHourInOneMeterPerSecond { get; } - protected abstract double KilometersPerMinutesInOneMeterPerSecond { get; } - protected abstract double KilometersPerSecondInOneMeterPerSecond { get; } - protected abstract double KnotsInOneMeterPerSecond { get; } - protected abstract double MetersPerHourInOneMeterPerSecond { get; } - protected abstract double MetersPerMinutesInOneMeterPerSecond { get; } - protected abstract double MetersPerSecondInOneMeterPerSecond { get; } - protected abstract double MicrometersPerMinutesInOneMeterPerSecond { get; } - protected abstract double MicrometersPerSecondInOneMeterPerSecond { get; } - protected abstract double MilesPerHourInOneMeterPerSecond { get; } - protected abstract double MillimetersPerHourInOneMeterPerSecond { get; } - protected abstract double MillimetersPerMinutesInOneMeterPerSecond { get; } - protected abstract double MillimetersPerSecondInOneMeterPerSecond { get; } - protected abstract double NanometersPerMinutesInOneMeterPerSecond { get; } - protected abstract double NanometersPerSecondInOneMeterPerSecond { get; } - protected abstract double UsSurveyFeetPerHourInOneMeterPerSecond { get; } - protected abstract double UsSurveyFeetPerMinuteInOneMeterPerSecond { get; } - protected abstract double UsSurveyFeetPerSecondInOneMeterPerSecond { get; } - protected abstract double YardsPerHourInOneMeterPerSecond { get; } - protected abstract double YardsPerMinuteInOneMeterPerSecond { get; } - protected abstract double YardsPerSecondInOneMeterPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentimetersPerHourTolerance { get { return 1e-5; } } - protected virtual double CentimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double CentimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double DecimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double FeetPerHourTolerance { get { return 1e-5; } } - protected virtual double FeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double FeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double InchesPerHourTolerance { get { return 1e-5; } } - protected virtual double InchesPerMinuteTolerance { get { return 1e-5; } } - protected virtual double InchesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilometersPerHourTolerance { get { return 1e-5; } } - protected virtual double KilometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double KilometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double KnotsTolerance { get { return 1e-5; } } - protected virtual double MetersPerHourTolerance { get { return 1e-5; } } - protected virtual double MetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MicrometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double MilesPerHourTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerHourTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double MillimetersPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanometersPerMinutesTolerance { get { return 1e-5; } } - protected virtual double NanometersPerSecondTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerHourTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerMinuteTolerance { get { return 1e-5; } } - protected virtual double UsSurveyFeetPerSecondTolerance { get { return 1e-5; } } - protected virtual double YardsPerHourTolerance { get { return 1e-5; } } - protected virtual double YardsPerMinuteTolerance { get { return 1e-5; } } - protected virtual double YardsPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void MeterPerSecondToSpeedUnits() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(CentimetersPerHourInOneMeterPerSecond, meterpersecond.CentimetersPerHour, CentimetersPerHourTolerance); - AssertEx.EqualTolerance(CentimetersPerMinutesInOneMeterPerSecond, meterpersecond.CentimetersPerMinutes, CentimetersPerMinutesTolerance); - AssertEx.EqualTolerance(CentimetersPerSecondInOneMeterPerSecond, meterpersecond.CentimetersPerSecond, CentimetersPerSecondTolerance); - AssertEx.EqualTolerance(DecimetersPerMinutesInOneMeterPerSecond, meterpersecond.DecimetersPerMinutes, DecimetersPerMinutesTolerance); - AssertEx.EqualTolerance(DecimetersPerSecondInOneMeterPerSecond, meterpersecond.DecimetersPerSecond, DecimetersPerSecondTolerance); - AssertEx.EqualTolerance(FeetPerHourInOneMeterPerSecond, meterpersecond.FeetPerHour, FeetPerHourTolerance); - AssertEx.EqualTolerance(FeetPerMinuteInOneMeterPerSecond, meterpersecond.FeetPerMinute, FeetPerMinuteTolerance); - AssertEx.EqualTolerance(FeetPerSecondInOneMeterPerSecond, meterpersecond.FeetPerSecond, FeetPerSecondTolerance); - AssertEx.EqualTolerance(InchesPerHourInOneMeterPerSecond, meterpersecond.InchesPerHour, InchesPerHourTolerance); - AssertEx.EqualTolerance(InchesPerMinuteInOneMeterPerSecond, meterpersecond.InchesPerMinute, InchesPerMinuteTolerance); - AssertEx.EqualTolerance(InchesPerSecondInOneMeterPerSecond, meterpersecond.InchesPerSecond, InchesPerSecondTolerance); - AssertEx.EqualTolerance(KilometersPerHourInOneMeterPerSecond, meterpersecond.KilometersPerHour, KilometersPerHourTolerance); - AssertEx.EqualTolerance(KilometersPerMinutesInOneMeterPerSecond, meterpersecond.KilometersPerMinutes, KilometersPerMinutesTolerance); - AssertEx.EqualTolerance(KilometersPerSecondInOneMeterPerSecond, meterpersecond.KilometersPerSecond, KilometersPerSecondTolerance); - AssertEx.EqualTolerance(KnotsInOneMeterPerSecond, meterpersecond.Knots, KnotsTolerance); - AssertEx.EqualTolerance(MetersPerHourInOneMeterPerSecond, meterpersecond.MetersPerHour, MetersPerHourTolerance); - AssertEx.EqualTolerance(MetersPerMinutesInOneMeterPerSecond, meterpersecond.MetersPerMinutes, MetersPerMinutesTolerance); - AssertEx.EqualTolerance(MetersPerSecondInOneMeterPerSecond, meterpersecond.MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(MicrometersPerMinutesInOneMeterPerSecond, meterpersecond.MicrometersPerMinutes, MicrometersPerMinutesTolerance); - AssertEx.EqualTolerance(MicrometersPerSecondInOneMeterPerSecond, meterpersecond.MicrometersPerSecond, MicrometersPerSecondTolerance); - AssertEx.EqualTolerance(MilesPerHourInOneMeterPerSecond, meterpersecond.MilesPerHour, MilesPerHourTolerance); - AssertEx.EqualTolerance(MillimetersPerHourInOneMeterPerSecond, meterpersecond.MillimetersPerHour, MillimetersPerHourTolerance); - AssertEx.EqualTolerance(MillimetersPerMinutesInOneMeterPerSecond, meterpersecond.MillimetersPerMinutes, MillimetersPerMinutesTolerance); - AssertEx.EqualTolerance(MillimetersPerSecondInOneMeterPerSecond, meterpersecond.MillimetersPerSecond, MillimetersPerSecondTolerance); - AssertEx.EqualTolerance(NanometersPerMinutesInOneMeterPerSecond, meterpersecond.NanometersPerMinutes, NanometersPerMinutesTolerance); - AssertEx.EqualTolerance(NanometersPerSecondInOneMeterPerSecond, meterpersecond.NanometersPerSecond, NanometersPerSecondTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerHourInOneMeterPerSecond, meterpersecond.UsSurveyFeetPerHour, UsSurveyFeetPerHourTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerMinuteInOneMeterPerSecond, meterpersecond.UsSurveyFeetPerMinute, UsSurveyFeetPerMinuteTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerSecondInOneMeterPerSecond, meterpersecond.UsSurveyFeetPerSecond, UsSurveyFeetPerSecondTolerance); - AssertEx.EqualTolerance(YardsPerHourInOneMeterPerSecond, meterpersecond.YardsPerHour, YardsPerHourTolerance); - AssertEx.EqualTolerance(YardsPerMinuteInOneMeterPerSecond, meterpersecond.YardsPerMinute, YardsPerMinuteTolerance); - AssertEx.EqualTolerance(YardsPerSecondInOneMeterPerSecond, meterpersecond.YardsPerSecond, YardsPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.CentimeterPerHour).CentimetersPerHour, CentimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.CentimeterPerMinute).CentimetersPerMinutes, CentimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.CentimeterPerSecond).CentimetersPerSecond, CentimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.DecimeterPerMinute).DecimetersPerMinutes, DecimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.DecimeterPerSecond).DecimetersPerSecond, DecimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.FootPerHour).FeetPerHour, FeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.FootPerMinute).FeetPerMinute, FeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.FootPerSecond).FeetPerSecond, FeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.InchPerHour).InchesPerHour, InchesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.InchPerMinute).InchesPerMinute, InchesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.InchPerSecond).InchesPerSecond, InchesPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.KilometerPerHour).KilometersPerHour, KilometersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.KilometerPerMinute).KilometersPerMinutes, KilometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.KilometerPerSecond).KilometersPerSecond, KilometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.Knot).Knots, KnotsTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MeterPerHour).MetersPerHour, MetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MeterPerMinute).MetersPerMinutes, MetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MeterPerSecond).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MicrometerPerMinute).MicrometersPerMinutes, MicrometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MicrometerPerSecond).MicrometersPerSecond, MicrometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MilePerHour).MilesPerHour, MilesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MillimeterPerHour).MillimetersPerHour, MillimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MillimeterPerMinute).MillimetersPerMinutes, MillimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.MillimeterPerSecond).MillimetersPerSecond, MillimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.NanometerPerMinute).NanometersPerMinutes, NanometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.NanometerPerSecond).NanometersPerSecond, NanometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.UsSurveyFootPerHour).UsSurveyFeetPerHour, UsSurveyFeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.UsSurveyFootPerMinute).UsSurveyFeetPerMinute, UsSurveyFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.UsSurveyFootPerSecond).UsSurveyFeetPerSecond, UsSurveyFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.YardPerHour).YardsPerHour, YardsPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.YardPerMinute).YardsPerMinute, YardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.From(1, SpeedUnit.YardPerSecond).YardsPerSecond, YardsPerSecondTolerance); - } - - [Fact] - public void As() - { - var meterpersecond = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(CentimetersPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.CentimeterPerHour), CentimetersPerHourTolerance); - AssertEx.EqualTolerance(CentimetersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.CentimeterPerMinute), CentimetersPerMinutesTolerance); - AssertEx.EqualTolerance(CentimetersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.CentimeterPerSecond), CentimetersPerSecondTolerance); - AssertEx.EqualTolerance(DecimetersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.DecimeterPerMinute), DecimetersPerMinutesTolerance); - AssertEx.EqualTolerance(DecimetersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.DecimeterPerSecond), DecimetersPerSecondTolerance); - AssertEx.EqualTolerance(FeetPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.FootPerHour), FeetPerHourTolerance); - AssertEx.EqualTolerance(FeetPerMinuteInOneMeterPerSecond, meterpersecond.As(SpeedUnit.FootPerMinute), FeetPerMinuteTolerance); - AssertEx.EqualTolerance(FeetPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.FootPerSecond), FeetPerSecondTolerance); - AssertEx.EqualTolerance(InchesPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.InchPerHour), InchesPerHourTolerance); - AssertEx.EqualTolerance(InchesPerMinuteInOneMeterPerSecond, meterpersecond.As(SpeedUnit.InchPerMinute), InchesPerMinuteTolerance); - AssertEx.EqualTolerance(InchesPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.InchPerSecond), InchesPerSecondTolerance); - AssertEx.EqualTolerance(KilometersPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.KilometerPerHour), KilometersPerHourTolerance); - AssertEx.EqualTolerance(KilometersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.KilometerPerMinute), KilometersPerMinutesTolerance); - AssertEx.EqualTolerance(KilometersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.KilometerPerSecond), KilometersPerSecondTolerance); - AssertEx.EqualTolerance(KnotsInOneMeterPerSecond, meterpersecond.As(SpeedUnit.Knot), KnotsTolerance); - AssertEx.EqualTolerance(MetersPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MeterPerHour), MetersPerHourTolerance); - AssertEx.EqualTolerance(MetersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MeterPerMinute), MetersPerMinutesTolerance); - AssertEx.EqualTolerance(MetersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MeterPerSecond), MetersPerSecondTolerance); - AssertEx.EqualTolerance(MicrometersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MicrometerPerMinute), MicrometersPerMinutesTolerance); - AssertEx.EqualTolerance(MicrometersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MicrometerPerSecond), MicrometersPerSecondTolerance); - AssertEx.EqualTolerance(MilesPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MilePerHour), MilesPerHourTolerance); - AssertEx.EqualTolerance(MillimetersPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MillimeterPerHour), MillimetersPerHourTolerance); - AssertEx.EqualTolerance(MillimetersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MillimeterPerMinute), MillimetersPerMinutesTolerance); - AssertEx.EqualTolerance(MillimetersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.MillimeterPerSecond), MillimetersPerSecondTolerance); - AssertEx.EqualTolerance(NanometersPerMinutesInOneMeterPerSecond, meterpersecond.As(SpeedUnit.NanometerPerMinute), NanometersPerMinutesTolerance); - AssertEx.EqualTolerance(NanometersPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.NanometerPerSecond), NanometersPerSecondTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.UsSurveyFootPerHour), UsSurveyFeetPerHourTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerMinuteInOneMeterPerSecond, meterpersecond.As(SpeedUnit.UsSurveyFootPerMinute), UsSurveyFeetPerMinuteTolerance); - AssertEx.EqualTolerance(UsSurveyFeetPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.UsSurveyFootPerSecond), UsSurveyFeetPerSecondTolerance); - AssertEx.EqualTolerance(YardsPerHourInOneMeterPerSecond, meterpersecond.As(SpeedUnit.YardPerHour), YardsPerHourTolerance); - AssertEx.EqualTolerance(YardsPerMinuteInOneMeterPerSecond, meterpersecond.As(SpeedUnit.YardPerMinute), YardsPerMinuteTolerance); - AssertEx.EqualTolerance(YardsPerSecondInOneMeterPerSecond, meterpersecond.As(SpeedUnit.YardPerSecond), YardsPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var meterpersecond = Speed.FromMetersPerSecond(1); - - var centimeterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerHour); - AssertEx.EqualTolerance(CentimetersPerHourInOneMeterPerSecond, (double)centimeterperhourQuantity.Value, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, centimeterperhourQuantity.Unit); - - var centimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerMinute); - AssertEx.EqualTolerance(CentimetersPerMinutesInOneMeterPerSecond, (double)centimeterperminuteQuantity.Value, CentimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, centimeterperminuteQuantity.Unit); - - var centimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.CentimeterPerSecond); - AssertEx.EqualTolerance(CentimetersPerSecondInOneMeterPerSecond, (double)centimeterpersecondQuantity.Value, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, centimeterpersecondQuantity.Unit); - - var decimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.DecimeterPerMinute); - AssertEx.EqualTolerance(DecimetersPerMinutesInOneMeterPerSecond, (double)decimeterperminuteQuantity.Value, DecimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, decimeterperminuteQuantity.Unit); - - var decimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.DecimeterPerSecond); - AssertEx.EqualTolerance(DecimetersPerSecondInOneMeterPerSecond, (double)decimeterpersecondQuantity.Value, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, decimeterpersecondQuantity.Unit); - - var footperhourQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerHour); - AssertEx.EqualTolerance(FeetPerHourInOneMeterPerSecond, (double)footperhourQuantity.Value, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, footperhourQuantity.Unit); - - var footperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerMinute); - AssertEx.EqualTolerance(FeetPerMinuteInOneMeterPerSecond, (double)footperminuteQuantity.Value, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, footperminuteQuantity.Unit); - - var footpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.FootPerSecond); - AssertEx.EqualTolerance(FeetPerSecondInOneMeterPerSecond, (double)footpersecondQuantity.Value, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, footpersecondQuantity.Unit); - - var inchperhourQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerHour); - AssertEx.EqualTolerance(InchesPerHourInOneMeterPerSecond, (double)inchperhourQuantity.Value, InchesPerHourTolerance); - Assert.Equal(SpeedUnit.InchPerHour, inchperhourQuantity.Unit); - - var inchperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerMinute); - AssertEx.EqualTolerance(InchesPerMinuteInOneMeterPerSecond, (double)inchperminuteQuantity.Value, InchesPerMinuteTolerance); - Assert.Equal(SpeedUnit.InchPerMinute, inchperminuteQuantity.Unit); - - var inchpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.InchPerSecond); - AssertEx.EqualTolerance(InchesPerSecondInOneMeterPerSecond, (double)inchpersecondQuantity.Value, InchesPerSecondTolerance); - Assert.Equal(SpeedUnit.InchPerSecond, inchpersecondQuantity.Unit); - - var kilometerperhourQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerHour); - AssertEx.EqualTolerance(KilometersPerHourInOneMeterPerSecond, (double)kilometerperhourQuantity.Value, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, kilometerperhourQuantity.Unit); - - var kilometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerMinute); - AssertEx.EqualTolerance(KilometersPerMinutesInOneMeterPerSecond, (double)kilometerperminuteQuantity.Value, KilometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, kilometerperminuteQuantity.Unit); - - var kilometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.KilometerPerSecond); - AssertEx.EqualTolerance(KilometersPerSecondInOneMeterPerSecond, (double)kilometerpersecondQuantity.Value, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, kilometerpersecondQuantity.Unit); - - var knotQuantity = meterpersecond.ToUnit(SpeedUnit.Knot); - AssertEx.EqualTolerance(KnotsInOneMeterPerSecond, (double)knotQuantity.Value, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, knotQuantity.Unit); - - var meterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerHour); - AssertEx.EqualTolerance(MetersPerHourInOneMeterPerSecond, (double)meterperhourQuantity.Value, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, meterperhourQuantity.Unit); - - var meterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerMinute); - AssertEx.EqualTolerance(MetersPerMinutesInOneMeterPerSecond, (double)meterperminuteQuantity.Value, MetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, meterperminuteQuantity.Unit); - - var meterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MeterPerSecond); - AssertEx.EqualTolerance(MetersPerSecondInOneMeterPerSecond, (double)meterpersecondQuantity.Value, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, meterpersecondQuantity.Unit); - - var micrometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MicrometerPerMinute); - AssertEx.EqualTolerance(MicrometersPerMinutesInOneMeterPerSecond, (double)micrometerperminuteQuantity.Value, MicrometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, micrometerperminuteQuantity.Unit); - - var micrometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MicrometerPerSecond); - AssertEx.EqualTolerance(MicrometersPerSecondInOneMeterPerSecond, (double)micrometerpersecondQuantity.Value, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, micrometerpersecondQuantity.Unit); - - var mileperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MilePerHour); - AssertEx.EqualTolerance(MilesPerHourInOneMeterPerSecond, (double)mileperhourQuantity.Value, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, mileperhourQuantity.Unit); - - var millimeterperhourQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerHour); - AssertEx.EqualTolerance(MillimetersPerHourInOneMeterPerSecond, (double)millimeterperhourQuantity.Value, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, millimeterperhourQuantity.Unit); - - var millimeterperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerMinute); - AssertEx.EqualTolerance(MillimetersPerMinutesInOneMeterPerSecond, (double)millimeterperminuteQuantity.Value, MillimetersPerMinutesTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, millimeterperminuteQuantity.Unit); - - var millimeterpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.MillimeterPerSecond); - AssertEx.EqualTolerance(MillimetersPerSecondInOneMeterPerSecond, (double)millimeterpersecondQuantity.Value, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, millimeterpersecondQuantity.Unit); - - var nanometerperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.NanometerPerMinute); - AssertEx.EqualTolerance(NanometersPerMinutesInOneMeterPerSecond, (double)nanometerperminuteQuantity.Value, NanometersPerMinutesTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, nanometerperminuteQuantity.Unit); - - var nanometerpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.NanometerPerSecond); - AssertEx.EqualTolerance(NanometersPerSecondInOneMeterPerSecond, (double)nanometerpersecondQuantity.Value, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, nanometerpersecondQuantity.Unit); - - var ussurveyfootperhourQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerHour); - AssertEx.EqualTolerance(UsSurveyFeetPerHourInOneMeterPerSecond, (double)ussurveyfootperhourQuantity.Value, UsSurveyFeetPerHourTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerHour, ussurveyfootperhourQuantity.Unit); - - var ussurveyfootperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerMinute); - AssertEx.EqualTolerance(UsSurveyFeetPerMinuteInOneMeterPerSecond, (double)ussurveyfootperminuteQuantity.Value, UsSurveyFeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerMinute, ussurveyfootperminuteQuantity.Unit); - - var ussurveyfootpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.UsSurveyFootPerSecond); - AssertEx.EqualTolerance(UsSurveyFeetPerSecondInOneMeterPerSecond, (double)ussurveyfootpersecondQuantity.Value, UsSurveyFeetPerSecondTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerSecond, ussurveyfootpersecondQuantity.Unit); - - var yardperhourQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerHour); - AssertEx.EqualTolerance(YardsPerHourInOneMeterPerSecond, (double)yardperhourQuantity.Value, YardsPerHourTolerance); - Assert.Equal(SpeedUnit.YardPerHour, yardperhourQuantity.Unit); - - var yardperminuteQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerMinute); - AssertEx.EqualTolerance(YardsPerMinuteInOneMeterPerSecond, (double)yardperminuteQuantity.Value, YardsPerMinuteTolerance); - Assert.Equal(SpeedUnit.YardPerMinute, yardperminuteQuantity.Unit); - - var yardpersecondQuantity = meterpersecond.ToUnit(SpeedUnit.YardPerSecond); - AssertEx.EqualTolerance(YardsPerSecondInOneMeterPerSecond, (double)yardpersecondQuantity.Value, YardsPerSecondTolerance); - Assert.Equal(SpeedUnit.YardPerSecond, yardpersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerHour(meterpersecond.CentimetersPerHour).MetersPerSecond, CentimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerMinutes(meterpersecond.CentimetersPerMinutes).MetersPerSecond, CentimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerSecond(meterpersecond.CentimetersPerSecond).MetersPerSecond, CentimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromDecimetersPerMinutes(meterpersecond.DecimetersPerMinutes).MetersPerSecond, DecimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromDecimetersPerSecond(meterpersecond.DecimetersPerSecond).MetersPerSecond, DecimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerHour(meterpersecond.FeetPerHour).MetersPerSecond, FeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerMinute(meterpersecond.FeetPerMinute).MetersPerSecond, FeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerSecond(meterpersecond.FeetPerSecond).MetersPerSecond, FeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerHour(meterpersecond.InchesPerHour).MetersPerSecond, InchesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerMinute(meterpersecond.InchesPerMinute).MetersPerSecond, InchesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerSecond(meterpersecond.InchesPerSecond).MetersPerSecond, InchesPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerHour(meterpersecond.KilometersPerHour).MetersPerSecond, KilometersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerMinutes(meterpersecond.KilometersPerMinutes).MetersPerSecond, KilometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerSecond(meterpersecond.KilometersPerSecond).MetersPerSecond, KilometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromKnots(meterpersecond.Knots).MetersPerSecond, KnotsTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerHour(meterpersecond.MetersPerHour).MetersPerSecond, MetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerMinutes(meterpersecond.MetersPerMinutes).MetersPerSecond, MetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerSecond(meterpersecond.MetersPerSecond).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromMicrometersPerMinutes(meterpersecond.MicrometersPerMinutes).MetersPerSecond, MicrometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromMicrometersPerSecond(meterpersecond.MicrometersPerSecond).MetersPerSecond, MicrometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromMilesPerHour(meterpersecond.MilesPerHour).MetersPerSecond, MilesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerHour(meterpersecond.MillimetersPerHour).MetersPerSecond, MillimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerMinutes(meterpersecond.MillimetersPerMinutes).MetersPerSecond, MillimetersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerSecond(meterpersecond.MillimetersPerSecond).MetersPerSecond, MillimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromNanometersPerMinutes(meterpersecond.NanometersPerMinutes).MetersPerSecond, NanometersPerMinutesTolerance); - AssertEx.EqualTolerance(1, Speed.FromNanometersPerSecond(meterpersecond.NanometersPerSecond).MetersPerSecond, NanometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerHour(meterpersecond.UsSurveyFeetPerHour).MetersPerSecond, UsSurveyFeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerMinute(meterpersecond.UsSurveyFeetPerMinute).MetersPerSecond, UsSurveyFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerSecond(meterpersecond.UsSurveyFeetPerSecond).MetersPerSecond, UsSurveyFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerHour(meterpersecond.YardsPerHour).MetersPerSecond, YardsPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerMinute(meterpersecond.YardsPerMinute).MetersPerSecond, YardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerSecond(meterpersecond.YardsPerSecond).MetersPerSecond, YardsPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Speed v = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Speed.FromMetersPerSecond(3)-v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Speed.FromMetersPerSecond(10)/5).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, Speed.FromMetersPerSecond(10)/Speed.FromMetersPerSecond(5), MetersPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Speed oneMeterPerSecond = Speed.FromMetersPerSecond(1); - Speed twoMetersPerSecond = Speed.FromMetersPerSecond(2); - - Assert.True(oneMeterPerSecond < twoMetersPerSecond); - Assert.True(oneMeterPerSecond <= twoMetersPerSecond); - Assert.True(twoMetersPerSecond > oneMeterPerSecond); - Assert.True(twoMetersPerSecond >= oneMeterPerSecond); - - Assert.False(oneMeterPerSecond > twoMetersPerSecond); - Assert.False(oneMeterPerSecond >= twoMetersPerSecond); - Assert.False(twoMetersPerSecond < oneMeterPerSecond); - Assert.False(twoMetersPerSecond <= oneMeterPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - Assert.Equal(0, meterpersecond.CompareTo(meterpersecond)); - Assert.True(meterpersecond.CompareTo(Speed.Zero) > 0); - Assert.True(Speed.Zero.CompareTo(meterpersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - Assert.Throws(() => meterpersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - Assert.Throws(() => meterpersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Speed a = Speed.FromMetersPerSecond(1); - Speed b = Speed.FromMetersPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Speed v = Speed.FromMetersPerSecond(1); - Assert.True(v.Equals(Speed.FromMetersPerSecond(1), Speed.FromMetersPerSecond(MetersPerSecondTolerance))); - Assert.False(v.Equals(Speed.Zero, Speed.FromMetersPerSecond(MetersPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - Assert.False(meterpersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - Assert.False(meterpersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpeedUnit.Undefined, Speed.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/TemperatureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TemperatureChangeRateTestsBase.g.cs deleted file mode 100644 index a5d3503dc7..0000000000 --- a/UnitsNet.Tests/GeneratedCode/TemperatureChangeRateTestsBase.g.cs +++ /dev/null @@ -1,287 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of TemperatureChangeRate. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class TemperatureChangeRateTestsBase - { - protected abstract double CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond { get; } - protected abstract double DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - protected abstract double NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double CentidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecadegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DecidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double DegreesCelsiusPerMinuteTolerance { get { return 1e-5; } } - protected virtual double DegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double HectodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double MicrodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double MillidegreesCelsiusPerSecondTolerance { get { return 1e-5; } } - protected virtual double NanodegreesCelsiusPerSecondTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void DegreeCelsiusPerSecondToTemperatureChangeRateUnits() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.CentidegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.DecadegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.DecidegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.DegreesCelsiusPerMinute, DegreesCelsiusPerMinuteTolerance); - AssertEx.EqualTolerance(DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.HectodegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.KilodegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.MicrodegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.MillidegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.NanodegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond).CentidegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond).DecadegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond).DecidegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeCelsiusPerMinute).DegreesCelsiusPerMinute, DegreesCelsiusPerMinuteTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond).HectodegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond).KilodegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond).MicrodegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond).MillidegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.From(1, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond).NanodegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); - } - - [Fact] - public void As() - { - var degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond), CentidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond), DecadegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond), DecidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute), DegreesCelsiusPerMinuteTolerance); - AssertEx.EqualTolerance(DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond), DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond), HectodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond), KilodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond), MicrodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond), MillidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, degreecelsiuspersecond.As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond), NanodegreesCelsiusPerSecondTolerance); - } - - [Fact] - public void ToUnit() - { - var degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - - var centidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(CentidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)centidegreecelsiuspersecondQuantity.Value, CentidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, centidegreecelsiuspersecondQuantity.Unit); - - var decadegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DecadegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)decadegreecelsiuspersecondQuantity.Value, DecadegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, decadegreecelsiuspersecondQuantity.Unit); - - var decidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DecidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)decidegreecelsiuspersecondQuantity.Value, DecidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, decidegreecelsiuspersecondQuantity.Unit); - - var degreecelsiusperminuteQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - AssertEx.EqualTolerance(DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond, (double)degreecelsiusperminuteQuantity.Value, DegreesCelsiusPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, degreecelsiusperminuteQuantity.Unit); - - var degreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - AssertEx.EqualTolerance(DegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)degreecelsiuspersecondQuantity.Value, DegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, degreecelsiuspersecondQuantity.Unit); - - var hectodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(HectodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)hectodegreecelsiuspersecondQuantity.Value, HectodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, hectodegreecelsiuspersecondQuantity.Unit); - - var kilodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(KilodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)kilodegreecelsiuspersecondQuantity.Value, KilodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, kilodegreecelsiuspersecondQuantity.Unit); - - var microdegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(MicrodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)microdegreecelsiuspersecondQuantity.Value, MicrodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, microdegreecelsiuspersecondQuantity.Unit); - - var millidegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(MillidegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)millidegreecelsiuspersecondQuantity.Value, MillidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, millidegreecelsiuspersecondQuantity.Unit); - - var nanodegreecelsiuspersecondQuantity = degreecelsiuspersecond.ToUnit(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond, (double)nanodegreecelsiuspersecondQuantity.Value, NanodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, nanodegreecelsiuspersecondQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(degreecelsiuspersecond.CentidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(degreecelsiuspersecond.DecadegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(degreecelsiuspersecond.DecidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesCelsiusPerMinute(degreecelsiuspersecond.DegreesCelsiusPerMinute).DegreesCelsiusPerSecond, DegreesCelsiusPerMinuteTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesCelsiusPerSecond(degreecelsiuspersecond.DegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(degreecelsiuspersecond.HectodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(degreecelsiuspersecond.KilodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(degreecelsiuspersecond.MicrodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(degreecelsiuspersecond.MillidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(degreecelsiuspersecond.NanodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - TemperatureChangeRate v = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(-1, -v.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(3)-v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(10)/5).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, TemperatureChangeRate.FromDegreesCelsiusPerSecond(10)/TemperatureChangeRate.FromDegreesCelsiusPerSecond(5), DegreesCelsiusPerSecondTolerance); - } - - [Fact] - public void ComparisonOperators() - { - TemperatureChangeRate oneDegreeCelsiusPerSecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - TemperatureChangeRate twoDegreesCelsiusPerSecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(2); - - Assert.True(oneDegreeCelsiusPerSecond < twoDegreesCelsiusPerSecond); - Assert.True(oneDegreeCelsiusPerSecond <= twoDegreesCelsiusPerSecond); - Assert.True(twoDegreesCelsiusPerSecond > oneDegreeCelsiusPerSecond); - Assert.True(twoDegreesCelsiusPerSecond >= oneDegreeCelsiusPerSecond); - - Assert.False(oneDegreeCelsiusPerSecond > twoDegreesCelsiusPerSecond); - Assert.False(oneDegreeCelsiusPerSecond >= twoDegreesCelsiusPerSecond); - Assert.False(twoDegreesCelsiusPerSecond < oneDegreeCelsiusPerSecond); - Assert.False(twoDegreesCelsiusPerSecond <= oneDegreeCelsiusPerSecond); - } - - [Fact] - public void CompareToIsImplemented() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.Equal(0, degreecelsiuspersecond.CompareTo(degreecelsiuspersecond)); - Assert.True(degreecelsiuspersecond.CompareTo(TemperatureChangeRate.Zero) > 0); - Assert.True(TemperatureChangeRate.Zero.CompareTo(degreecelsiuspersecond) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.Throws(() => degreecelsiuspersecond.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.Throws(() => degreecelsiuspersecond.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - TemperatureChangeRate a = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - TemperatureChangeRate b = TemperatureChangeRate.FromDegreesCelsiusPerSecond(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - TemperatureChangeRate v = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.True(v.Equals(TemperatureChangeRate.FromDegreesCelsiusPerSecond(1), TemperatureChangeRate.FromDegreesCelsiusPerSecond(DegreesCelsiusPerSecondTolerance))); - Assert.False(v.Equals(TemperatureChangeRate.Zero, TemperatureChangeRate.FromDegreesCelsiusPerSecond(DegreesCelsiusPerSecondTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.False(degreecelsiuspersecond.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.False(degreecelsiuspersecond.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureChangeRateUnit.Undefined, TemperatureChangeRate.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/TemperatureDeltaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TemperatureDeltaTestsBase.g.cs deleted file mode 100644 index 3fd5e0a093..0000000000 --- a/UnitsNet.Tests/GeneratedCode/TemperatureDeltaTestsBase.g.cs +++ /dev/null @@ -1,347 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of TemperatureDelta. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class TemperatureDeltaTestsBase - { - protected abstract double DegreesCelsiusInOneKelvin { get; } - protected abstract double DegreesCelsiusDeltaInOneKelvin { get; } - protected abstract double DegreesDelisleInOneKelvin { get; } - protected abstract double DegreesDelisleDeltaInOneKelvin { get; } - protected abstract double DegreesFahrenheitInOneKelvin { get; } - protected abstract double DegreesFahrenheitDeltaInOneKelvin { get; } - protected abstract double DegreesNewtonInOneKelvin { get; } - protected abstract double DegreesNewtonDeltaInOneKelvin { get; } - protected abstract double DegreesRankineInOneKelvin { get; } - protected abstract double DegreesRankineDeltaInOneKelvin { get; } - protected abstract double DegreesReaumurInOneKelvin { get; } - protected abstract double DegreesReaumurDeltaInOneKelvin { get; } - protected abstract double DegreesRoemerInOneKelvin { get; } - protected abstract double DegreesRoemerDeltaInOneKelvin { get; } - protected abstract double KelvinsInOneKelvin { get; } - protected abstract double KelvinsDeltaInOneKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelsiusTolerance { get { return 1e-5; } } - protected virtual double DegreesCelsiusDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesDelisleTolerance { get { return 1e-5; } } - protected virtual double DegreesDelisleDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesNewtonTolerance { get { return 1e-5; } } - protected virtual double DegreesNewtonDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesRankineTolerance { get { return 1e-5; } } - protected virtual double DegreesRankineDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesReaumurTolerance { get { return 1e-5; } } - protected virtual double DegreesReaumurDeltaTolerance { get { return 1e-5; } } - protected virtual double DegreesRoemerTolerance { get { return 1e-5; } } - protected virtual double DegreesRoemerDeltaTolerance { get { return 1e-5; } } - protected virtual double KelvinsTolerance { get { return 1e-5; } } - protected virtual double KelvinsDeltaTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KelvinToTemperatureDeltaUnits() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, kelvin.DegreesCelsius, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(DegreesCelsiusDeltaInOneKelvin, kelvin.DegreesCelsiusDelta, DegreesCelsiusDeltaTolerance); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, kelvin.DegreesDelisle, DegreesDelisleTolerance); - AssertEx.EqualTolerance(DegreesDelisleDeltaInOneKelvin, kelvin.DegreesDelisleDelta, DegreesDelisleDeltaTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, kelvin.DegreesFahrenheit, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitDeltaInOneKelvin, kelvin.DegreesFahrenheitDelta, DegreesFahrenheitDeltaTolerance); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, kelvin.DegreesNewton, DegreesNewtonTolerance); - AssertEx.EqualTolerance(DegreesNewtonDeltaInOneKelvin, kelvin.DegreesNewtonDelta, DegreesNewtonDeltaTolerance); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, kelvin.DegreesRankine, DegreesRankineTolerance); - AssertEx.EqualTolerance(DegreesRankineDeltaInOneKelvin, kelvin.DegreesRankineDelta, DegreesRankineDeltaTolerance); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, kelvin.DegreesReaumur, DegreesReaumurTolerance); - AssertEx.EqualTolerance(DegreesReaumurDeltaInOneKelvin, kelvin.DegreesReaumurDelta, DegreesReaumurDeltaTolerance); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, kelvin.DegreesRoemer, DegreesRoemerTolerance); - AssertEx.EqualTolerance(DegreesRoemerDeltaInOneKelvin, kelvin.DegreesRoemerDelta, DegreesRoemerDeltaTolerance); - AssertEx.EqualTolerance(KelvinsInOneKelvin, kelvin.Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(KelvinsDeltaInOneKelvin, kelvin.KelvinsDelta, KelvinsDeltaTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeCelsius).DegreesCelsius, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeCelsiusDelta).DegreesCelsiusDelta, DegreesCelsiusDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeDelisle).DegreesDelisle, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeDelisleDelta).DegreesDelisleDelta, DegreesDelisleDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeFahrenheit).DegreesFahrenheit, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeFahrenheitDelta).DegreesFahrenheitDelta, DegreesFahrenheitDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeNewton).DegreesNewton, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeNewtonDelta).DegreesNewtonDelta, DegreesNewtonDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRankine).DegreesRankine, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRankineDelta).DegreesRankineDelta, DegreesRankineDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeReaumur).DegreesReaumur, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeReaumurDelta).DegreesReaumurDelta, DegreesReaumurDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRoemer).DegreesRoemer, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRoemerDelta).DegreesRoemerDelta, DegreesRoemerDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.Kelvin).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.From(1, TemperatureDeltaUnit.KelvinDelta).KelvinsDelta, KelvinsDeltaTolerance); - } - - [Fact] - public void As() - { - var kelvin = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeCelsius), DegreesCelsiusTolerance); - AssertEx.EqualTolerance(DegreesCelsiusDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeCelsiusDelta), DegreesCelsiusDeltaTolerance); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeDelisle), DegreesDelisleTolerance); - AssertEx.EqualTolerance(DegreesDelisleDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeDelisleDelta), DegreesDelisleDeltaTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeFahrenheit), DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeFahrenheitDelta), DegreesFahrenheitDeltaTolerance); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeNewton), DegreesNewtonTolerance); - AssertEx.EqualTolerance(DegreesNewtonDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeNewtonDelta), DegreesNewtonDeltaTolerance); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeRankine), DegreesRankineTolerance); - AssertEx.EqualTolerance(DegreesRankineDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeRankineDelta), DegreesRankineDeltaTolerance); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeReaumur), DegreesReaumurTolerance); - AssertEx.EqualTolerance(DegreesReaumurDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeReaumurDelta), DegreesReaumurDeltaTolerance); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeRoemer), DegreesRoemerTolerance); - AssertEx.EqualTolerance(DegreesRoemerDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.DegreeRoemerDelta), DegreesRoemerDeltaTolerance); - AssertEx.EqualTolerance(KelvinsInOneKelvin, kelvin.As(TemperatureDeltaUnit.Kelvin), KelvinsTolerance); - AssertEx.EqualTolerance(KelvinsDeltaInOneKelvin, kelvin.As(TemperatureDeltaUnit.KelvinDelta), KelvinsDeltaTolerance); - } - - [Fact] - public void ToUnit() - { - var kelvin = TemperatureDelta.FromKelvins(1); - - var degreecelsiusQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeCelsius); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, (double)degreecelsiusQuantity.Value, DegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeCelsius, degreecelsiusQuantity.Unit); - - var degreecelsiusdeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeCelsiusDelta); - AssertEx.EqualTolerance(DegreesCelsiusDeltaInOneKelvin, (double)degreecelsiusdeltaQuantity.Value, DegreesCelsiusDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeCelsiusDelta, degreecelsiusdeltaQuantity.Unit); - - var degreedelisleQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeDelisle); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, (double)degreedelisleQuantity.Value, DegreesDelisleTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeDelisle, degreedelisleQuantity.Unit); - - var degreedelisledeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeDelisleDelta); - AssertEx.EqualTolerance(DegreesDelisleDeltaInOneKelvin, (double)degreedelisledeltaQuantity.Value, DegreesDelisleDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeDelisleDelta, degreedelisledeltaQuantity.Unit); - - var degreefahrenheitQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, (double)degreefahrenheitQuantity.Value, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheit, degreefahrenheitQuantity.Unit); - - var degreefahrenheitdeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeFahrenheitDelta); - AssertEx.EqualTolerance(DegreesFahrenheitDeltaInOneKelvin, (double)degreefahrenheitdeltaQuantity.Value, DegreesFahrenheitDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheitDelta, degreefahrenheitdeltaQuantity.Unit); - - var degreenewtonQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeNewton); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, (double)degreenewtonQuantity.Value, DegreesNewtonTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeNewton, degreenewtonQuantity.Unit); - - var degreenewtondeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeNewtonDelta); - AssertEx.EqualTolerance(DegreesNewtonDeltaInOneKelvin, (double)degreenewtondeltaQuantity.Value, DegreesNewtonDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeNewtonDelta, degreenewtondeltaQuantity.Unit); - - var degreerankineQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRankine); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, (double)degreerankineQuantity.Value, DegreesRankineTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRankine, degreerankineQuantity.Unit); - - var degreerankinedeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRankineDelta); - AssertEx.EqualTolerance(DegreesRankineDeltaInOneKelvin, (double)degreerankinedeltaQuantity.Value, DegreesRankineDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRankineDelta, degreerankinedeltaQuantity.Unit); - - var degreereaumurQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeReaumur); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, (double)degreereaumurQuantity.Value, DegreesReaumurTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeReaumur, degreereaumurQuantity.Unit); - - var degreereaumurdeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeReaumurDelta); - AssertEx.EqualTolerance(DegreesReaumurDeltaInOneKelvin, (double)degreereaumurdeltaQuantity.Value, DegreesReaumurDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeReaumurDelta, degreereaumurdeltaQuantity.Unit); - - var degreeroemerQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRoemer); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, (double)degreeroemerQuantity.Value, DegreesRoemerTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRoemer, degreeroemerQuantity.Unit); - - var degreeroemerdeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.DegreeRoemerDelta); - AssertEx.EqualTolerance(DegreesRoemerDeltaInOneKelvin, (double)degreeroemerdeltaQuantity.Value, DegreesRoemerDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRoemerDelta, degreeroemerdeltaQuantity.Unit); - - var kelvinQuantity = kelvin.ToUnit(TemperatureDeltaUnit.Kelvin); - AssertEx.EqualTolerance(KelvinsInOneKelvin, (double)kelvinQuantity.Value, KelvinsTolerance); - Assert.Equal(TemperatureDeltaUnit.Kelvin, kelvinQuantity.Unit); - - var kelvindeltaQuantity = kelvin.ToUnit(TemperatureDeltaUnit.KelvinDelta); - AssertEx.EqualTolerance(KelvinsDeltaInOneKelvin, (double)kelvindeltaQuantity.Value, KelvinsDeltaTolerance); - Assert.Equal(TemperatureDeltaUnit.KelvinDelta, kelvindeltaQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesCelsiusDelta(kelvin.DegreesCelsiusDelta).Kelvins, DegreesCelsiusDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesDelisleDelta(kelvin.DegreesDelisleDelta).Kelvins, DegreesDelisleDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesFahrenheitDelta(kelvin.DegreesFahrenheitDelta).Kelvins, DegreesFahrenheitDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesNewton(kelvin.DegreesNewton).Kelvins, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesNewtonDelta(kelvin.DegreesNewtonDelta).Kelvins, DegreesNewtonDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRankine(kelvin.DegreesRankine).Kelvins, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRankineDelta(kelvin.DegreesRankineDelta).Kelvins, DegreesRankineDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesReaumurDelta(kelvin.DegreesReaumurDelta).Kelvins, DegreesReaumurDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRoemerDelta(kelvin.DegreesRoemerDelta).Kelvins, DegreesRoemerDeltaTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromKelvins(kelvin.Kelvins).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromKelvinsDelta(kelvin.KelvinsDelta).Kelvins, KelvinsDeltaTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - TemperatureDelta v = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(-1, -v.Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (TemperatureDelta.FromKelvins(3)-v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (v + v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(10, (v*10).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(10, (10*v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (TemperatureDelta.FromKelvins(10)/5).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, TemperatureDelta.FromKelvins(10)/TemperatureDelta.FromKelvins(5), KelvinsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - TemperatureDelta oneKelvin = TemperatureDelta.FromKelvins(1); - TemperatureDelta twoKelvins = TemperatureDelta.FromKelvins(2); - - Assert.True(oneKelvin < twoKelvins); - Assert.True(oneKelvin <= twoKelvins); - Assert.True(twoKelvins > oneKelvin); - Assert.True(twoKelvins >= oneKelvin); - - Assert.False(oneKelvin > twoKelvins); - Assert.False(oneKelvin >= twoKelvins); - Assert.False(twoKelvins < oneKelvin); - Assert.False(twoKelvins <= oneKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.Equal(0, kelvin.CompareTo(kelvin)); - Assert.True(kelvin.CompareTo(TemperatureDelta.Zero) > 0); - Assert.True(TemperatureDelta.Zero.CompareTo(kelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.Throws(() => kelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.Throws(() => kelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - TemperatureDelta a = TemperatureDelta.FromKelvins(1); - TemperatureDelta b = TemperatureDelta.FromKelvins(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - TemperatureDelta v = TemperatureDelta.FromKelvins(1); - Assert.True(v.Equals(TemperatureDelta.FromKelvins(1), TemperatureDelta.FromKelvins(KelvinsTolerance))); - Assert.False(v.Equals(TemperatureDelta.Zero, TemperatureDelta.FromKelvins(KelvinsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.False(kelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.False(kelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureDeltaUnit.Undefined, TemperatureDelta.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/TemperatureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TemperatureTestsBase.g.cs deleted file mode 100644 index e855ea235c..0000000000 --- a/UnitsNet.Tests/GeneratedCode/TemperatureTestsBase.g.cs +++ /dev/null @@ -1,255 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Temperature. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class TemperatureTestsBase - { - protected abstract double DegreesCelsiusInOneKelvin { get; } - protected abstract double DegreesDelisleInOneKelvin { get; } - protected abstract double DegreesFahrenheitInOneKelvin { get; } - protected abstract double DegreesNewtonInOneKelvin { get; } - protected abstract double DegreesRankineInOneKelvin { get; } - protected abstract double DegreesReaumurInOneKelvin { get; } - protected abstract double DegreesRoemerInOneKelvin { get; } - protected abstract double KelvinsInOneKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double DegreesCelsiusTolerance { get { return 1e-5; } } - protected virtual double DegreesDelisleTolerance { get { return 1e-5; } } - protected virtual double DegreesFahrenheitTolerance { get { return 1e-5; } } - protected virtual double DegreesNewtonTolerance { get { return 1e-5; } } - protected virtual double DegreesRankineTolerance { get { return 1e-5; } } - protected virtual double DegreesReaumurTolerance { get { return 1e-5; } } - protected virtual double DegreesRoemerTolerance { get { return 1e-5; } } - protected virtual double KelvinsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void KelvinToTemperatureUnits() - { - Temperature kelvin = Temperature.FromKelvins(1); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, kelvin.DegreesCelsius, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, kelvin.DegreesDelisle, DegreesDelisleTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, kelvin.DegreesFahrenheit, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, kelvin.DegreesNewton, DegreesNewtonTolerance); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, kelvin.DegreesRankine, DegreesRankineTolerance); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, kelvin.DegreesReaumur, DegreesReaumurTolerance); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, kelvin.DegreesRoemer, DegreesRoemerTolerance); - AssertEx.EqualTolerance(KelvinsInOneKelvin, kelvin.Kelvins, KelvinsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeCelsius).DegreesCelsius, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeDelisle).DegreesDelisle, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeFahrenheit).DegreesFahrenheit, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeNewton).DegreesNewton, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeRankine).DegreesRankine, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeReaumur).DegreesReaumur, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.DegreeRoemer).DegreesRoemer, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, Temperature.From(1, TemperatureUnit.Kelvin).Kelvins, KelvinsTolerance); - } - - [Fact] - public void As() - { - var kelvin = Temperature.FromKelvins(1); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, kelvin.As(TemperatureUnit.DegreeCelsius), DegreesCelsiusTolerance); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, kelvin.As(TemperatureUnit.DegreeDelisle), DegreesDelisleTolerance); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, kelvin.As(TemperatureUnit.DegreeFahrenheit), DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, kelvin.As(TemperatureUnit.DegreeNewton), DegreesNewtonTolerance); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, kelvin.As(TemperatureUnit.DegreeRankine), DegreesRankineTolerance); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, kelvin.As(TemperatureUnit.DegreeReaumur), DegreesReaumurTolerance); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, kelvin.As(TemperatureUnit.DegreeRoemer), DegreesRoemerTolerance); - AssertEx.EqualTolerance(KelvinsInOneKelvin, kelvin.As(TemperatureUnit.Kelvin), KelvinsTolerance); - } - - [Fact] - public void ToUnit() - { - var kelvin = Temperature.FromKelvins(1); - - var degreecelsiusQuantity = kelvin.ToUnit(TemperatureUnit.DegreeCelsius); - AssertEx.EqualTolerance(DegreesCelsiusInOneKelvin, (double)degreecelsiusQuantity.Value, DegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.DegreeCelsius, degreecelsiusQuantity.Unit); - - var degreedelisleQuantity = kelvin.ToUnit(TemperatureUnit.DegreeDelisle); - AssertEx.EqualTolerance(DegreesDelisleInOneKelvin, (double)degreedelisleQuantity.Value, DegreesDelisleTolerance); - Assert.Equal(TemperatureUnit.DegreeDelisle, degreedelisleQuantity.Unit); - - var degreefahrenheitQuantity = kelvin.ToUnit(TemperatureUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(DegreesFahrenheitInOneKelvin, (double)degreefahrenheitQuantity.Value, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureUnit.DegreeFahrenheit, degreefahrenheitQuantity.Unit); - - var degreenewtonQuantity = kelvin.ToUnit(TemperatureUnit.DegreeNewton); - AssertEx.EqualTolerance(DegreesNewtonInOneKelvin, (double)degreenewtonQuantity.Value, DegreesNewtonTolerance); - Assert.Equal(TemperatureUnit.DegreeNewton, degreenewtonQuantity.Unit); - - var degreerankineQuantity = kelvin.ToUnit(TemperatureUnit.DegreeRankine); - AssertEx.EqualTolerance(DegreesRankineInOneKelvin, (double)degreerankineQuantity.Value, DegreesRankineTolerance); - Assert.Equal(TemperatureUnit.DegreeRankine, degreerankineQuantity.Unit); - - var degreereaumurQuantity = kelvin.ToUnit(TemperatureUnit.DegreeReaumur); - AssertEx.EqualTolerance(DegreesReaumurInOneKelvin, (double)degreereaumurQuantity.Value, DegreesReaumurTolerance); - Assert.Equal(TemperatureUnit.DegreeReaumur, degreereaumurQuantity.Unit); - - var degreeroemerQuantity = kelvin.ToUnit(TemperatureUnit.DegreeRoemer); - AssertEx.EqualTolerance(DegreesRoemerInOneKelvin, (double)degreeroemerQuantity.Value, DegreesRoemerTolerance); - Assert.Equal(TemperatureUnit.DegreeRoemer, degreeroemerQuantity.Unit); - - var kelvinQuantity = kelvin.ToUnit(TemperatureUnit.Kelvin); - AssertEx.EqualTolerance(KelvinsInOneKelvin, (double)kelvinQuantity.Value, KelvinsTolerance); - Assert.Equal(TemperatureUnit.Kelvin, kelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Temperature kelvin = Temperature.FromKelvins(1); - AssertEx.EqualTolerance(1, Temperature.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesNewton(kelvin.DegreesNewton).Kelvins, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesRankine(kelvin.DegreesRankine).Kelvins, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, Temperature.FromKelvins(kelvin.Kelvins).Kelvins, KelvinsTolerance); - } - - - [Fact] - public void ComparisonOperators() - { - Temperature oneKelvin = Temperature.FromKelvins(1); - Temperature twoKelvins = Temperature.FromKelvins(2); - - Assert.True(oneKelvin < twoKelvins); - Assert.True(oneKelvin <= twoKelvins); - Assert.True(twoKelvins > oneKelvin); - Assert.True(twoKelvins >= oneKelvin); - - Assert.False(oneKelvin > twoKelvins); - Assert.False(oneKelvin >= twoKelvins); - Assert.False(twoKelvins < oneKelvin); - Assert.False(twoKelvins <= oneKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.Equal(0, kelvin.CompareTo(kelvin)); - Assert.True(kelvin.CompareTo(Temperature.Zero) > 0); - Assert.True(Temperature.Zero.CompareTo(kelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.Throws(() => kelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.Throws(() => kelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Temperature a = Temperature.FromKelvins(1); - Temperature b = Temperature.FromKelvins(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Temperature v = Temperature.FromKelvins(1); - Assert.True(v.Equals(Temperature.FromKelvins(1), Temperature.FromKelvins(KelvinsTolerance))); - Assert.False(v.Equals(Temperature.Zero, Temperature.FromKelvins(KelvinsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.False(kelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.False(kelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureUnit.Undefined, Temperature.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ThermalConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ThermalConductivityTestsBase.g.cs deleted file mode 100644 index 0f59b697b8..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ThermalConductivityTestsBase.g.cs +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ThermalConductivity. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ThermalConductivityTestsBase - { - protected abstract double BtusPerHourFootFahrenheitInOneWattPerMeterKelvin { get; } - protected abstract double WattsPerMeterKelvinInOneWattPerMeterKelvin { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BtusPerHourFootFahrenheitTolerance { get { return 1e-5; } } - protected virtual double WattsPerMeterKelvinTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void WattPerMeterKelvinToThermalConductivityUnits() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(BtusPerHourFootFahrenheitInOneWattPerMeterKelvin, wattpermeterkelvin.BtusPerHourFootFahrenheit, BtusPerHourFootFahrenheitTolerance); - AssertEx.EqualTolerance(WattsPerMeterKelvinInOneWattPerMeterKelvin, wattpermeterkelvin.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ThermalConductivity.From(1, ThermalConductivityUnit.BtuPerHourFootFahrenheit).BtusPerHourFootFahrenheit, BtusPerHourFootFahrenheitTolerance); - AssertEx.EqualTolerance(1, ThermalConductivity.From(1, ThermalConductivityUnit.WattPerMeterKelvin).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - } - - [Fact] - public void As() - { - var wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(BtusPerHourFootFahrenheitInOneWattPerMeterKelvin, wattpermeterkelvin.As(ThermalConductivityUnit.BtuPerHourFootFahrenheit), BtusPerHourFootFahrenheitTolerance); - AssertEx.EqualTolerance(WattsPerMeterKelvinInOneWattPerMeterKelvin, wattpermeterkelvin.As(ThermalConductivityUnit.WattPerMeterKelvin), WattsPerMeterKelvinTolerance); - } - - [Fact] - public void ToUnit() - { - var wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - - var btuperhourfootfahrenheitQuantity = wattpermeterkelvin.ToUnit(ThermalConductivityUnit.BtuPerHourFootFahrenheit); - AssertEx.EqualTolerance(BtusPerHourFootFahrenheitInOneWattPerMeterKelvin, (double)btuperhourfootfahrenheitQuantity.Value, BtusPerHourFootFahrenheitTolerance); - Assert.Equal(ThermalConductivityUnit.BtuPerHourFootFahrenheit, btuperhourfootfahrenheitQuantity.Unit); - - var wattpermeterkelvinQuantity = wattpermeterkelvin.ToUnit(ThermalConductivityUnit.WattPerMeterKelvin); - AssertEx.EqualTolerance(WattsPerMeterKelvinInOneWattPerMeterKelvin, (double)wattpermeterkelvinQuantity.Value, WattsPerMeterKelvinTolerance); - Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, wattpermeterkelvinQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(1, ThermalConductivity.FromBtusPerHourFootFahrenheit(wattpermeterkelvin.BtusPerHourFootFahrenheit).WattsPerMeterKelvin, BtusPerHourFootFahrenheitTolerance); - AssertEx.EqualTolerance(1, ThermalConductivity.FromWattsPerMeterKelvin(wattpermeterkelvin.WattsPerMeterKelvin).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ThermalConductivity v = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(-1, -v.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (ThermalConductivity.FromWattsPerMeterKelvin(3)-v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (ThermalConductivity.FromWattsPerMeterKelvin(10)/5).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, ThermalConductivity.FromWattsPerMeterKelvin(10)/ThermalConductivity.FromWattsPerMeterKelvin(5), WattsPerMeterKelvinTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ThermalConductivity oneWattPerMeterKelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - ThermalConductivity twoWattsPerMeterKelvin = ThermalConductivity.FromWattsPerMeterKelvin(2); - - Assert.True(oneWattPerMeterKelvin < twoWattsPerMeterKelvin); - Assert.True(oneWattPerMeterKelvin <= twoWattsPerMeterKelvin); - Assert.True(twoWattsPerMeterKelvin > oneWattPerMeterKelvin); - Assert.True(twoWattsPerMeterKelvin >= oneWattPerMeterKelvin); - - Assert.False(oneWattPerMeterKelvin > twoWattsPerMeterKelvin); - Assert.False(oneWattPerMeterKelvin >= twoWattsPerMeterKelvin); - Assert.False(twoWattsPerMeterKelvin < oneWattPerMeterKelvin); - Assert.False(twoWattsPerMeterKelvin <= oneWattPerMeterKelvin); - } - - [Fact] - public void CompareToIsImplemented() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.Equal(0, wattpermeterkelvin.CompareTo(wattpermeterkelvin)); - Assert.True(wattpermeterkelvin.CompareTo(ThermalConductivity.Zero) > 0); - Assert.True(ThermalConductivity.Zero.CompareTo(wattpermeterkelvin) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.Throws(() => wattpermeterkelvin.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.Throws(() => wattpermeterkelvin.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ThermalConductivity a = ThermalConductivity.FromWattsPerMeterKelvin(1); - ThermalConductivity b = ThermalConductivity.FromWattsPerMeterKelvin(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ThermalConductivity v = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.True(v.Equals(ThermalConductivity.FromWattsPerMeterKelvin(1), ThermalConductivity.FromWattsPerMeterKelvin(WattsPerMeterKelvinTolerance))); - Assert.False(v.Equals(ThermalConductivity.Zero, ThermalConductivity.FromWattsPerMeterKelvin(WattsPerMeterKelvinTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.False(wattpermeterkelvin.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.False(wattpermeterkelvin.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ThermalConductivityUnit.Undefined, ThermalConductivity.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/ThermalResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/ThermalResistanceTestsBase.g.cs deleted file mode 100644 index b2f1989ed0..0000000000 --- a/UnitsNet.Tests/GeneratedCode/ThermalResistanceTestsBase.g.cs +++ /dev/null @@ -1,237 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of ThermalResistance. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ThermalResistanceTestsBase - { - protected abstract double HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt { get; } - protected abstract double SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt { get; } - protected abstract double SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt { get; } - protected abstract double SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt { get; } - protected abstract double SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double HourSquareFeetDegreesFahrenheitPerBtuTolerance { get { return 1e-5; } } - protected virtual double SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance { get { return 1e-5; } } - protected virtual double SquareCentimeterKelvinsPerWattTolerance { get { return 1e-5; } } - protected virtual double SquareMeterDegreesCelsiusPerWattTolerance { get { return 1e-5; } } - protected virtual double SquareMeterKelvinsPerKilowattTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void SquareMeterKelvinPerKilowattToThermalResistanceUnits() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.HourSquareFeetDegreesFahrenheitPerBtu, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - AssertEx.EqualTolerance(SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.SquareCentimeterHourDegreesCelsiusPerKilocalorie, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - AssertEx.EqualTolerance(SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.SquareCentimeterKelvinsPerWatt, SquareCentimeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.SquareMeterDegreesCelsiusPerWatt, SquareMeterDegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, ThermalResistance.From(1, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu).HourSquareFeetDegreesFahrenheitPerBtu, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.From(1, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie).SquareCentimeterHourDegreesCelsiusPerKilocalorie, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.From(1, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt).SquareCentimeterKelvinsPerWatt, SquareCentimeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.From(1, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt).SquareMeterDegreesCelsiusPerWatt, SquareMeterDegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.From(1, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - } - - [Fact] - public void As() - { - var squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu), HourSquareFeetDegreesFahrenheitPerBtuTolerance); - AssertEx.EqualTolerance(SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie), SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - AssertEx.EqualTolerance(SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt), SquareCentimeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt), SquareMeterDegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowatt.As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), SquareMeterKelvinsPerKilowattTolerance); - } - - [Fact] - public void ToUnit() - { - var squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - - var hoursquarefeetdegreefahrenheitperbtuQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - AssertEx.EqualTolerance(HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerKilowatt, (double)hoursquarefeetdegreefahrenheitperbtuQuantity.Value, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - Assert.Equal(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, hoursquarefeetdegreefahrenheitperbtuQuantity.Unit); - - var squarecentimeterhourdegreecelsiusperkilocalorieQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - AssertEx.EqualTolerance(SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerKilowatt, (double)squarecentimeterhourdegreecelsiusperkilocalorieQuantity.Value, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - Assert.Equal(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, squarecentimeterhourdegreecelsiusperkilocalorieQuantity.Unit); - - var squarecentimeterkelvinperwattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - AssertEx.EqualTolerance(SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt, (double)squarecentimeterkelvinperwattQuantity.Value, SquareCentimeterKelvinsPerWattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, squarecentimeterkelvinperwattQuantity.Unit); - - var squaremeterdegreecelsiusperwattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - AssertEx.EqualTolerance(SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerKilowatt, (double)squaremeterdegreecelsiusperwattQuantity.Value, SquareMeterDegreesCelsiusPerWattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, squaremeterdegreecelsiusperwattQuantity.Unit); - - var squaremeterkelvinperkilowattQuantity = squaremeterkelvinperkilowatt.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - AssertEx.EqualTolerance(SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt, (double)squaremeterkelvinperkilowattQuantity.Value, SquareMeterKelvinsPerKilowattTolerance); - Assert.Equal(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, squaremeterkelvinperkilowattQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(1, ThermalResistance.FromHourSquareFeetDegreesFahrenheitPerBtu(squaremeterkelvinperkilowatt.HourSquareFeetDegreesFahrenheitPerBtu).SquareMeterKelvinsPerKilowatt, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(squaremeterkelvinperkilowatt.SquareCentimeterHourDegreesCelsiusPerKilocalorie).SquareMeterKelvinsPerKilowatt, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.FromSquareCentimeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareCentimeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt, SquareCentimeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.FromSquareMeterDegreesCelsiusPerWatt(squaremeterkelvinperkilowatt.SquareMeterDegreesCelsiusPerWatt).SquareMeterKelvinsPerKilowatt, SquareMeterDegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.FromSquareMeterKelvinsPerKilowatt(squaremeterkelvinperkilowatt.SquareMeterKelvinsPerKilowatt).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - ThermalResistance v = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(-1, -v.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (ThermalResistance.FromSquareMeterKelvinsPerKilowatt(3)-v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (ThermalResistance.FromSquareMeterKelvinsPerKilowatt(10)/5).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, ThermalResistance.FromSquareMeterKelvinsPerKilowatt(10)/ThermalResistance.FromSquareMeterKelvinsPerKilowatt(5), SquareMeterKelvinsPerKilowattTolerance); - } - - [Fact] - public void ComparisonOperators() - { - ThermalResistance oneSquareMeterKelvinPerKilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - ThermalResistance twoSquareMeterKelvinsPerKilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(2); - - Assert.True(oneSquareMeterKelvinPerKilowatt < twoSquareMeterKelvinsPerKilowatt); - Assert.True(oneSquareMeterKelvinPerKilowatt <= twoSquareMeterKelvinsPerKilowatt); - Assert.True(twoSquareMeterKelvinsPerKilowatt > oneSquareMeterKelvinPerKilowatt); - Assert.True(twoSquareMeterKelvinsPerKilowatt >= oneSquareMeterKelvinPerKilowatt); - - Assert.False(oneSquareMeterKelvinPerKilowatt > twoSquareMeterKelvinsPerKilowatt); - Assert.False(oneSquareMeterKelvinPerKilowatt >= twoSquareMeterKelvinsPerKilowatt); - Assert.False(twoSquareMeterKelvinsPerKilowatt < oneSquareMeterKelvinPerKilowatt); - Assert.False(twoSquareMeterKelvinsPerKilowatt <= oneSquareMeterKelvinPerKilowatt); - } - - [Fact] - public void CompareToIsImplemented() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.Equal(0, squaremeterkelvinperkilowatt.CompareTo(squaremeterkelvinperkilowatt)); - Assert.True(squaremeterkelvinperkilowatt.CompareTo(ThermalResistance.Zero) > 0); - Assert.True(ThermalResistance.Zero.CompareTo(squaremeterkelvinperkilowatt) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.Throws(() => squaremeterkelvinperkilowatt.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.Throws(() => squaremeterkelvinperkilowatt.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - ThermalResistance a = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - ThermalResistance b = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - ThermalResistance v = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.True(v.Equals(ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1), ThermalResistance.FromSquareMeterKelvinsPerKilowatt(SquareMeterKelvinsPerKilowattTolerance))); - Assert.False(v.Equals(ThermalResistance.Zero, ThermalResistance.FromSquareMeterKelvinsPerKilowatt(SquareMeterKelvinsPerKilowattTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.False(squaremeterkelvinperkilowatt.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - ThermalResistance squaremeterkelvinperkilowatt = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.False(squaremeterkelvinperkilowatt.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ThermalResistanceUnit.Undefined, ThermalResistance.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TorqueTestsBase.g.cs deleted file mode 100644 index 908ec3f2f0..0000000000 --- a/UnitsNet.Tests/GeneratedCode/TorqueTestsBase.g.cs +++ /dev/null @@ -1,397 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Torque. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class TorqueTestsBase - { - protected abstract double KilogramForceCentimetersInOneNewtonMeter { get; } - protected abstract double KilogramForceMetersInOneNewtonMeter { get; } - protected abstract double KilogramForceMillimetersInOneNewtonMeter { get; } - protected abstract double KilonewtonCentimetersInOneNewtonMeter { get; } - protected abstract double KilonewtonMetersInOneNewtonMeter { get; } - protected abstract double KilonewtonMillimetersInOneNewtonMeter { get; } - protected abstract double KilopoundForceFeetInOneNewtonMeter { get; } - protected abstract double KilopoundForceInchesInOneNewtonMeter { get; } - protected abstract double MeganewtonCentimetersInOneNewtonMeter { get; } - protected abstract double MeganewtonMetersInOneNewtonMeter { get; } - protected abstract double MeganewtonMillimetersInOneNewtonMeter { get; } - protected abstract double MegapoundForceFeetInOneNewtonMeter { get; } - protected abstract double MegapoundForceInchesInOneNewtonMeter { get; } - protected abstract double NewtonCentimetersInOneNewtonMeter { get; } - protected abstract double NewtonMetersInOneNewtonMeter { get; } - protected abstract double NewtonMillimetersInOneNewtonMeter { get; } - protected abstract double PoundForceFeetInOneNewtonMeter { get; } - protected abstract double PoundForceInchesInOneNewtonMeter { get; } - protected abstract double TonneForceCentimetersInOneNewtonMeter { get; } - protected abstract double TonneForceMetersInOneNewtonMeter { get; } - protected abstract double TonneForceMillimetersInOneNewtonMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double KilogramForceCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMetersTolerance { get { return 1e-5; } } - protected virtual double KilogramForceMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMetersTolerance { get { return 1e-5; } } - protected virtual double KilonewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double KilopoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double MeganewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMetersTolerance { get { return 1e-5; } } - protected virtual double MeganewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double MegapoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double NewtonCentimetersTolerance { get { return 1e-5; } } - protected virtual double NewtonMetersTolerance { get { return 1e-5; } } - protected virtual double NewtonMillimetersTolerance { get { return 1e-5; } } - protected virtual double PoundForceFeetTolerance { get { return 1e-5; } } - protected virtual double PoundForceInchesTolerance { get { return 1e-5; } } - protected virtual double TonneForceCentimetersTolerance { get { return 1e-5; } } - protected virtual double TonneForceMetersTolerance { get { return 1e-5; } } - protected virtual double TonneForceMillimetersTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void NewtonMeterToTorqueUnits() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(KilogramForceCentimetersInOneNewtonMeter, newtonmeter.KilogramForceCentimeters, KilogramForceCentimetersTolerance); - AssertEx.EqualTolerance(KilogramForceMetersInOneNewtonMeter, newtonmeter.KilogramForceMeters, KilogramForceMetersTolerance); - AssertEx.EqualTolerance(KilogramForceMillimetersInOneNewtonMeter, newtonmeter.KilogramForceMillimeters, KilogramForceMillimetersTolerance); - AssertEx.EqualTolerance(KilonewtonCentimetersInOneNewtonMeter, newtonmeter.KilonewtonCentimeters, KilonewtonCentimetersTolerance); - AssertEx.EqualTolerance(KilonewtonMetersInOneNewtonMeter, newtonmeter.KilonewtonMeters, KilonewtonMetersTolerance); - AssertEx.EqualTolerance(KilonewtonMillimetersInOneNewtonMeter, newtonmeter.KilonewtonMillimeters, KilonewtonMillimetersTolerance); - AssertEx.EqualTolerance(KilopoundForceFeetInOneNewtonMeter, newtonmeter.KilopoundForceFeet, KilopoundForceFeetTolerance); - AssertEx.EqualTolerance(KilopoundForceInchesInOneNewtonMeter, newtonmeter.KilopoundForceInches, KilopoundForceInchesTolerance); - AssertEx.EqualTolerance(MeganewtonCentimetersInOneNewtonMeter, newtonmeter.MeganewtonCentimeters, MeganewtonCentimetersTolerance); - AssertEx.EqualTolerance(MeganewtonMetersInOneNewtonMeter, newtonmeter.MeganewtonMeters, MeganewtonMetersTolerance); - AssertEx.EqualTolerance(MeganewtonMillimetersInOneNewtonMeter, newtonmeter.MeganewtonMillimeters, MeganewtonMillimetersTolerance); - AssertEx.EqualTolerance(MegapoundForceFeetInOneNewtonMeter, newtonmeter.MegapoundForceFeet, MegapoundForceFeetTolerance); - AssertEx.EqualTolerance(MegapoundForceInchesInOneNewtonMeter, newtonmeter.MegapoundForceInches, MegapoundForceInchesTolerance); - AssertEx.EqualTolerance(NewtonCentimetersInOneNewtonMeter, newtonmeter.NewtonCentimeters, NewtonCentimetersTolerance); - AssertEx.EqualTolerance(NewtonMetersInOneNewtonMeter, newtonmeter.NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(NewtonMillimetersInOneNewtonMeter, newtonmeter.NewtonMillimeters, NewtonMillimetersTolerance); - AssertEx.EqualTolerance(PoundForceFeetInOneNewtonMeter, newtonmeter.PoundForceFeet, PoundForceFeetTolerance); - AssertEx.EqualTolerance(PoundForceInchesInOneNewtonMeter, newtonmeter.PoundForceInches, PoundForceInchesTolerance); - AssertEx.EqualTolerance(TonneForceCentimetersInOneNewtonMeter, newtonmeter.TonneForceCentimeters, TonneForceCentimetersTolerance); - AssertEx.EqualTolerance(TonneForceMetersInOneNewtonMeter, newtonmeter.TonneForceMeters, TonneForceMetersTolerance); - AssertEx.EqualTolerance(TonneForceMillimetersInOneNewtonMeter, newtonmeter.TonneForceMillimeters, TonneForceMillimetersTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilogramForceCentimeter).KilogramForceCentimeters, KilogramForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilogramForceMeter).KilogramForceMeters, KilogramForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilogramForceMillimeter).KilogramForceMillimeters, KilogramForceMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilonewtonCentimeter).KilonewtonCentimeters, KilonewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilonewtonMeter).KilonewtonMeters, KilonewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilonewtonMillimeter).KilonewtonMillimeters, KilonewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilopoundForceFoot).KilopoundForceFeet, KilopoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.KilopoundForceInch).KilopoundForceInches, KilopoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.MeganewtonCentimeter).MeganewtonCentimeters, MeganewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.MeganewtonMeter).MeganewtonMeters, MeganewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.MeganewtonMillimeter).MeganewtonMillimeters, MeganewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.MegapoundForceFoot).MegapoundForceFeet, MegapoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.MegapoundForceInch).MegapoundForceInches, MegapoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.NewtonCentimeter).NewtonCentimeters, NewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.NewtonMeter).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.NewtonMillimeter).NewtonMillimeters, NewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.PoundForceFoot).PoundForceFeet, PoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.PoundForceInch).PoundForceInches, PoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.TonneForceCentimeter).TonneForceCentimeters, TonneForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.TonneForceMeter).TonneForceMeters, TonneForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.From(1, TorqueUnit.TonneForceMillimeter).TonneForceMillimeters, TonneForceMillimetersTolerance); - } - - [Fact] - public void As() - { - var newtonmeter = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(KilogramForceCentimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilogramForceCentimeter), KilogramForceCentimetersTolerance); - AssertEx.EqualTolerance(KilogramForceMetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilogramForceMeter), KilogramForceMetersTolerance); - AssertEx.EqualTolerance(KilogramForceMillimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilogramForceMillimeter), KilogramForceMillimetersTolerance); - AssertEx.EqualTolerance(KilonewtonCentimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilonewtonCentimeter), KilonewtonCentimetersTolerance); - AssertEx.EqualTolerance(KilonewtonMetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilonewtonMeter), KilonewtonMetersTolerance); - AssertEx.EqualTolerance(KilonewtonMillimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilonewtonMillimeter), KilonewtonMillimetersTolerance); - AssertEx.EqualTolerance(KilopoundForceFeetInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilopoundForceFoot), KilopoundForceFeetTolerance); - AssertEx.EqualTolerance(KilopoundForceInchesInOneNewtonMeter, newtonmeter.As(TorqueUnit.KilopoundForceInch), KilopoundForceInchesTolerance); - AssertEx.EqualTolerance(MeganewtonCentimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.MeganewtonCentimeter), MeganewtonCentimetersTolerance); - AssertEx.EqualTolerance(MeganewtonMetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.MeganewtonMeter), MeganewtonMetersTolerance); - AssertEx.EqualTolerance(MeganewtonMillimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.MeganewtonMillimeter), MeganewtonMillimetersTolerance); - AssertEx.EqualTolerance(MegapoundForceFeetInOneNewtonMeter, newtonmeter.As(TorqueUnit.MegapoundForceFoot), MegapoundForceFeetTolerance); - AssertEx.EqualTolerance(MegapoundForceInchesInOneNewtonMeter, newtonmeter.As(TorqueUnit.MegapoundForceInch), MegapoundForceInchesTolerance); - AssertEx.EqualTolerance(NewtonCentimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.NewtonCentimeter), NewtonCentimetersTolerance); - AssertEx.EqualTolerance(NewtonMetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.NewtonMeter), NewtonMetersTolerance); - AssertEx.EqualTolerance(NewtonMillimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.NewtonMillimeter), NewtonMillimetersTolerance); - AssertEx.EqualTolerance(PoundForceFeetInOneNewtonMeter, newtonmeter.As(TorqueUnit.PoundForceFoot), PoundForceFeetTolerance); - AssertEx.EqualTolerance(PoundForceInchesInOneNewtonMeter, newtonmeter.As(TorqueUnit.PoundForceInch), PoundForceInchesTolerance); - AssertEx.EqualTolerance(TonneForceCentimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.TonneForceCentimeter), TonneForceCentimetersTolerance); - AssertEx.EqualTolerance(TonneForceMetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.TonneForceMeter), TonneForceMetersTolerance); - AssertEx.EqualTolerance(TonneForceMillimetersInOneNewtonMeter, newtonmeter.As(TorqueUnit.TonneForceMillimeter), TonneForceMillimetersTolerance); - } - - [Fact] - public void ToUnit() - { - var newtonmeter = Torque.FromNewtonMeters(1); - - var kilogramforcecentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceCentimeter); - AssertEx.EqualTolerance(KilogramForceCentimetersInOneNewtonMeter, (double)kilogramforcecentimeterQuantity.Value, KilogramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceCentimeter, kilogramforcecentimeterQuantity.Unit); - - var kilogramforcemeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceMeter); - AssertEx.EqualTolerance(KilogramForceMetersInOneNewtonMeter, (double)kilogramforcemeterQuantity.Value, KilogramForceMetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMeter, kilogramforcemeterQuantity.Unit); - - var kilogramforcemillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilogramForceMillimeter); - AssertEx.EqualTolerance(KilogramForceMillimetersInOneNewtonMeter, (double)kilogramforcemillimeterQuantity.Value, KilogramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMillimeter, kilogramforcemillimeterQuantity.Unit); - - var kilonewtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonCentimeter); - AssertEx.EqualTolerance(KilonewtonCentimetersInOneNewtonMeter, (double)kilonewtoncentimeterQuantity.Value, KilonewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonCentimeter, kilonewtoncentimeterQuantity.Unit); - - var kilonewtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonMeter); - AssertEx.EqualTolerance(KilonewtonMetersInOneNewtonMeter, (double)kilonewtonmeterQuantity.Value, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, kilonewtonmeterQuantity.Unit); - - var kilonewtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.KilonewtonMillimeter); - AssertEx.EqualTolerance(KilonewtonMillimetersInOneNewtonMeter, (double)kilonewtonmillimeterQuantity.Value, KilonewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMillimeter, kilonewtonmillimeterQuantity.Unit); - - var kilopoundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.KilopoundForceFoot); - AssertEx.EqualTolerance(KilopoundForceFeetInOneNewtonMeter, (double)kilopoundforcefootQuantity.Value, KilopoundForceFeetTolerance); - Assert.Equal(TorqueUnit.KilopoundForceFoot, kilopoundforcefootQuantity.Unit); - - var kilopoundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.KilopoundForceInch); - AssertEx.EqualTolerance(KilopoundForceInchesInOneNewtonMeter, (double)kilopoundforceinchQuantity.Value, KilopoundForceInchesTolerance); - Assert.Equal(TorqueUnit.KilopoundForceInch, kilopoundforceinchQuantity.Unit); - - var meganewtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonCentimeter); - AssertEx.EqualTolerance(MeganewtonCentimetersInOneNewtonMeter, (double)meganewtoncentimeterQuantity.Value, MeganewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonCentimeter, meganewtoncentimeterQuantity.Unit); - - var meganewtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonMeter); - AssertEx.EqualTolerance(MeganewtonMetersInOneNewtonMeter, (double)meganewtonmeterQuantity.Value, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, meganewtonmeterQuantity.Unit); - - var meganewtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.MeganewtonMillimeter); - AssertEx.EqualTolerance(MeganewtonMillimetersInOneNewtonMeter, (double)meganewtonmillimeterQuantity.Value, MeganewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMillimeter, meganewtonmillimeterQuantity.Unit); - - var megapoundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.MegapoundForceFoot); - AssertEx.EqualTolerance(MegapoundForceFeetInOneNewtonMeter, (double)megapoundforcefootQuantity.Value, MegapoundForceFeetTolerance); - Assert.Equal(TorqueUnit.MegapoundForceFoot, megapoundforcefootQuantity.Unit); - - var megapoundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.MegapoundForceInch); - AssertEx.EqualTolerance(MegapoundForceInchesInOneNewtonMeter, (double)megapoundforceinchQuantity.Value, MegapoundForceInchesTolerance); - Assert.Equal(TorqueUnit.MegapoundForceInch, megapoundforceinchQuantity.Unit); - - var newtoncentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonCentimeter); - AssertEx.EqualTolerance(NewtonCentimetersInOneNewtonMeter, (double)newtoncentimeterQuantity.Value, NewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.NewtonCentimeter, newtoncentimeterQuantity.Unit); - - var newtonmeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonMeter); - AssertEx.EqualTolerance(NewtonMetersInOneNewtonMeter, (double)newtonmeterQuantity.Value, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, newtonmeterQuantity.Unit); - - var newtonmillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.NewtonMillimeter); - AssertEx.EqualTolerance(NewtonMillimetersInOneNewtonMeter, (double)newtonmillimeterQuantity.Value, NewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.NewtonMillimeter, newtonmillimeterQuantity.Unit); - - var poundforcefootQuantity = newtonmeter.ToUnit(TorqueUnit.PoundForceFoot); - AssertEx.EqualTolerance(PoundForceFeetInOneNewtonMeter, (double)poundforcefootQuantity.Value, PoundForceFeetTolerance); - Assert.Equal(TorqueUnit.PoundForceFoot, poundforcefootQuantity.Unit); - - var poundforceinchQuantity = newtonmeter.ToUnit(TorqueUnit.PoundForceInch); - AssertEx.EqualTolerance(PoundForceInchesInOneNewtonMeter, (double)poundforceinchQuantity.Value, PoundForceInchesTolerance); - Assert.Equal(TorqueUnit.PoundForceInch, poundforceinchQuantity.Unit); - - var tonneforcecentimeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceCentimeter); - AssertEx.EqualTolerance(TonneForceCentimetersInOneNewtonMeter, (double)tonneforcecentimeterQuantity.Value, TonneForceCentimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceCentimeter, tonneforcecentimeterQuantity.Unit); - - var tonneforcemeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceMeter); - AssertEx.EqualTolerance(TonneForceMetersInOneNewtonMeter, (double)tonneforcemeterQuantity.Value, TonneForceMetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMeter, tonneforcemeterQuantity.Unit); - - var tonneforcemillimeterQuantity = newtonmeter.ToUnit(TorqueUnit.TonneForceMillimeter); - AssertEx.EqualTolerance(TonneForceMillimetersInOneNewtonMeter, (double)tonneforcemillimeterQuantity.Value, TonneForceMillimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMillimeter, tonneforcemillimeterQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceCentimeters(newtonmeter.KilogramForceCentimeters).NewtonMeters, KilogramForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceMeters(newtonmeter.KilogramForceMeters).NewtonMeters, KilogramForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceMillimeters(newtonmeter.KilogramForceMillimeters).NewtonMeters, KilogramForceMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonCentimeters(newtonmeter.KilonewtonCentimeters).NewtonMeters, KilonewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonMeters(newtonmeter.KilonewtonMeters).NewtonMeters, KilonewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonMillimeters(newtonmeter.KilonewtonMillimeters).NewtonMeters, KilonewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilopoundForceFeet(newtonmeter.KilopoundForceFeet).NewtonMeters, KilopoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilopoundForceInches(newtonmeter.KilopoundForceInches).NewtonMeters, KilopoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonCentimeters(newtonmeter.MeganewtonCentimeters).NewtonMeters, MeganewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonMeters(newtonmeter.MeganewtonMeters).NewtonMeters, MeganewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonMillimeters(newtonmeter.MeganewtonMillimeters).NewtonMeters, MeganewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMegapoundForceFeet(newtonmeter.MegapoundForceFeet).NewtonMeters, MegapoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromMegapoundForceInches(newtonmeter.MegapoundForceInches).NewtonMeters, MegapoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonCentimeters(newtonmeter.NewtonCentimeters).NewtonMeters, NewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonMeters(newtonmeter.NewtonMeters).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonMillimeters(newtonmeter.NewtonMillimeters).NewtonMeters, NewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromPoundForceFeet(newtonmeter.PoundForceFeet).NewtonMeters, PoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromPoundForceInches(newtonmeter.PoundForceInches).NewtonMeters, PoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceCentimeters(newtonmeter.TonneForceCentimeters).NewtonMeters, TonneForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceMeters(newtonmeter.TonneForceMeters).NewtonMeters, TonneForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceMillimeters(newtonmeter.TonneForceMillimeters).NewtonMeters, TonneForceMillimetersTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Torque v = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(-1, -v.NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (Torque.FromNewtonMeters(3)-v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (Torque.FromNewtonMeters(10)/5).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, Torque.FromNewtonMeters(10)/Torque.FromNewtonMeters(5), NewtonMetersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Torque oneNewtonMeter = Torque.FromNewtonMeters(1); - Torque twoNewtonMeters = Torque.FromNewtonMeters(2); - - Assert.True(oneNewtonMeter < twoNewtonMeters); - Assert.True(oneNewtonMeter <= twoNewtonMeters); - Assert.True(twoNewtonMeters > oneNewtonMeter); - Assert.True(twoNewtonMeters >= oneNewtonMeter); - - Assert.False(oneNewtonMeter > twoNewtonMeters); - Assert.False(oneNewtonMeter >= twoNewtonMeters); - Assert.False(twoNewtonMeters < oneNewtonMeter); - Assert.False(twoNewtonMeters <= oneNewtonMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - Assert.Equal(0, newtonmeter.CompareTo(newtonmeter)); - Assert.True(newtonmeter.CompareTo(Torque.Zero) > 0); - Assert.True(Torque.Zero.CompareTo(newtonmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - Assert.Throws(() => newtonmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - Assert.Throws(() => newtonmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Torque a = Torque.FromNewtonMeters(1); - Torque b = Torque.FromNewtonMeters(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Torque v = Torque.FromNewtonMeters(1); - Assert.True(v.Equals(Torque.FromNewtonMeters(1), Torque.FromNewtonMeters(NewtonMetersTolerance))); - Assert.False(v.Equals(Torque.Zero, Torque.FromNewtonMeters(NewtonMetersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - Assert.False(newtonmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Torque newtonmeter = Torque.FromNewtonMeters(1); - Assert.False(newtonmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TorqueUnit.Undefined, Torque.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/VitaminATestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/VitaminATestsBase.g.cs deleted file mode 100644 index 8d75f4a4cc..0000000000 --- a/UnitsNet.Tests/GeneratedCode/VitaminATestsBase.g.cs +++ /dev/null @@ -1,197 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of VitaminA. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class VitaminATestsBase - { - protected abstract double InternationalUnitsInOneInternationalUnit { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double InternationalUnitsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void InternationalUnitToVitaminAUnits() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(InternationalUnitsInOneInternationalUnit, internationalunit.InternationalUnits, InternationalUnitsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, VitaminA.From(1, VitaminAUnit.InternationalUnit).InternationalUnits, InternationalUnitsTolerance); - } - - [Fact] - public void As() - { - var internationalunit = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(InternationalUnitsInOneInternationalUnit, internationalunit.As(VitaminAUnit.InternationalUnit), InternationalUnitsTolerance); - } - - [Fact] - public void ToUnit() - { - var internationalunit = VitaminA.FromInternationalUnits(1); - - var internationalunitQuantity = internationalunit.ToUnit(VitaminAUnit.InternationalUnit); - AssertEx.EqualTolerance(InternationalUnitsInOneInternationalUnit, (double)internationalunitQuantity.Value, InternationalUnitsTolerance); - Assert.Equal(VitaminAUnit.InternationalUnit, internationalunitQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(1, VitaminA.FromInternationalUnits(internationalunit.InternationalUnits).InternationalUnits, InternationalUnitsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - VitaminA v = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(-1, -v.InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (VitaminA.FromInternationalUnits(3)-v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (v + v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(10, (v*10).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(10, (10*v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (VitaminA.FromInternationalUnits(10)/5).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, VitaminA.FromInternationalUnits(10)/VitaminA.FromInternationalUnits(5), InternationalUnitsTolerance); - } - - [Fact] - public void ComparisonOperators() - { - VitaminA oneInternationalUnit = VitaminA.FromInternationalUnits(1); - VitaminA twoInternationalUnits = VitaminA.FromInternationalUnits(2); - - Assert.True(oneInternationalUnit < twoInternationalUnits); - Assert.True(oneInternationalUnit <= twoInternationalUnits); - Assert.True(twoInternationalUnits > oneInternationalUnit); - Assert.True(twoInternationalUnits >= oneInternationalUnit); - - Assert.False(oneInternationalUnit > twoInternationalUnits); - Assert.False(oneInternationalUnit >= twoInternationalUnits); - Assert.False(twoInternationalUnits < oneInternationalUnit); - Assert.False(twoInternationalUnits <= oneInternationalUnit); - } - - [Fact] - public void CompareToIsImplemented() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.Equal(0, internationalunit.CompareTo(internationalunit)); - Assert.True(internationalunit.CompareTo(VitaminA.Zero) > 0); - Assert.True(VitaminA.Zero.CompareTo(internationalunit) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.Throws(() => internationalunit.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.Throws(() => internationalunit.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - VitaminA a = VitaminA.FromInternationalUnits(1); - VitaminA b = VitaminA.FromInternationalUnits(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - VitaminA v = VitaminA.FromInternationalUnits(1); - Assert.True(v.Equals(VitaminA.FromInternationalUnits(1), VitaminA.FromInternationalUnits(InternationalUnitsTolerance))); - Assert.False(v.Equals(VitaminA.Zero, VitaminA.FromInternationalUnits(InternationalUnitsTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.False(internationalunit.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.False(internationalunit.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VitaminAUnit.Undefined, VitaminA.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/VolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/VolumeFlowTestsBase.g.cs index 6bb664c183..2c4830cfe7 100644 --- a/UnitsNet.Tests/GeneratedCode/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/VolumeFlowTestsBase.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -113,6 +112,25 @@ public abstract partial class VolumeFlowTestsBase protected virtual double UsGallonsPerSecondTolerance { get { return 1e-5; } } // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new VolumeFlow((double)0.0, VolumeFlowUnit.Undefined)); + } + + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new VolumeFlow(double.PositiveInfinity, VolumeFlowUnit.CubicMeterPerSecond)); + Assert.Throws(() => new VolumeFlow(double.NegativeInfinity, VolumeFlowUnit.CubicMeterPerSecond)); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new VolumeFlow(double.NaN, VolumeFlowUnit.CubicMeterPerSecond)); + } + [Fact] public void CubicMeterPerSecondToVolumeFlowUnits() { @@ -150,7 +168,7 @@ public void CubicMeterPerSecondToVolumeFlowUnits() [Fact] public void FromValueAndUnit() { - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CentilitersPerMinute).CentilitersPerMinute, CentilitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CentiliterPerMinute).CentilitersPerMinute, CentilitersPerMinuteTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicDecimeterPerMinute).CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicFootPerHour).CubicFeetPerHour, CubicFeetPerHourTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicFootPerMinute).CubicFeetPerMinute, CubicFeetPerMinuteTolerance); @@ -162,29 +180,42 @@ public void FromValueAndUnit() AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerHour).CubicYardsPerHour, CubicYardsPerHourTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerMinute).CubicYardsPerMinute, CubicYardsPerMinuteTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerSecond).CubicYardsPerSecond, CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.DecilitersPerMinute).DecilitersPerMinute, DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.KilolitersPerMinute).KilolitersPerMinute, KilolitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.DeciliterPerMinute).DecilitersPerMinute, DecilitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.KiloliterPerMinute).KilolitersPerMinute, KilolitersPerMinuteTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.KilousGallonsPerMinute).KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LitersPerHour).LitersPerHour, LitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LitersPerMinute).LitersPerMinute, LitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LitersPerSecond).LitersPerSecond, LitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.MicrolitersPerMinute).MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.MillilitersPerMinute).MillilitersPerMinute, MillilitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LiterPerHour).LitersPerHour, LitersPerHourTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LiterPerMinute).LitersPerMinute, LitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.LiterPerSecond).LitersPerSecond, LitersPerSecondTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.MicroliterPerMinute).MicrolitersPerMinute, MicrolitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.MilliliterPerMinute).MillilitersPerMinute, MillilitersPerMinuteTolerance); AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.MillionUsGallonsPerDay).MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.NanolitersPerMinute).NanolitersPerMinute, NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelsPerDay).OilBarrelsPerDay, OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelsPerHour).OilBarrelsPerHour, OilBarrelsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelsPerMinute).OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonsPerHour).UsGallonsPerHour, UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonsPerMinute).UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonsPerSecond).UsGallonsPerSecond, UsGallonsPerSecondTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerMinute).NanolitersPerMinute, NanolitersPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerDay).OilBarrelsPerDay, OilBarrelsPerDayTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerHour).OilBarrelsPerHour, OilBarrelsPerHourTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerMinute).OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerHour).UsGallonsPerHour, UsGallonsPerHourTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerMinute).UsGallonsPerMinute, UsGallonsPerMinuteTolerance); + AssertEx.EqualTolerance(1, VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerSecond).UsGallonsPerSecond, UsGallonsPerSecondTolerance); + } + + [Fact] + public void FromCubicMetersPerSecond_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => VolumeFlow.FromCubicMetersPerSecond(double.PositiveInfinity)); + Assert.Throws(() => VolumeFlow.FromCubicMetersPerSecond(double.NegativeInfinity)); + } + + [Fact] + public void FromCubicMetersPerSecond_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => VolumeFlow.FromCubicMetersPerSecond(double.NaN)); } [Fact] public void As() { var cubicmeterpersecond = VolumeFlow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CentilitersPerMinute), CentilitersPerMinuteTolerance); + AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CentiliterPerMinute), CentilitersPerMinuteTolerance); AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicDecimeterPerMinute), CubicDecimetersPerMinuteTolerance); AssertEx.EqualTolerance(CubicFeetPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicFootPerHour), CubicFeetPerHourTolerance); AssertEx.EqualTolerance(CubicFeetPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicFootPerMinute), CubicFeetPerMinuteTolerance); @@ -196,22 +227,22 @@ public void As() AssertEx.EqualTolerance(CubicYardsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicYardPerHour), CubicYardsPerHourTolerance); AssertEx.EqualTolerance(CubicYardsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicYardPerMinute), CubicYardsPerMinuteTolerance); AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.CubicYardPerSecond), CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.DecilitersPerMinute), DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.KilolitersPerMinute), KilolitersPerMinuteTolerance); + AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.DeciliterPerMinute), DecilitersPerMinuteTolerance); + AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.KiloliterPerMinute), KilolitersPerMinuteTolerance); AssertEx.EqualTolerance(KilousGallonsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.KilousGallonsPerMinute), KilousGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LitersPerHour), LitersPerHourTolerance); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LitersPerMinute), LitersPerMinuteTolerance); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LitersPerSecond), LitersPerSecondTolerance); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MicrolitersPerMinute), MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MillilitersPerMinute), MillilitersPerMinuteTolerance); + AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LiterPerHour), LitersPerHourTolerance); + AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LiterPerMinute), LitersPerMinuteTolerance); + AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.LiterPerSecond), LitersPerSecondTolerance); + AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MicroliterPerMinute), MicrolitersPerMinuteTolerance); + AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MilliliterPerMinute), MillilitersPerMinuteTolerance); AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MillionUsGallonsPerDay), MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.NanolitersPerMinute), NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelsPerDay), OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(OilBarrelsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelsPerHour), OilBarrelsPerHourTolerance); - AssertEx.EqualTolerance(OilBarrelsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelsPerMinute), OilBarrelsPerMinuteTolerance); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonsPerHour), UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonsPerMinute), UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonsPerSecond), UsGallonsPerSecondTolerance); + AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.NanoliterPerMinute), NanolitersPerMinuteTolerance); + AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelPerDay), OilBarrelsPerDayTolerance); + AssertEx.EqualTolerance(OilBarrelsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelPerHour), OilBarrelsPerHourTolerance); + AssertEx.EqualTolerance(OilBarrelsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.OilBarrelPerMinute), OilBarrelsPerMinuteTolerance); + AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonPerHour), UsGallonsPerHourTolerance); + AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonPerMinute), UsGallonsPerMinuteTolerance); + AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.UsGallonPerSecond), UsGallonsPerSecondTolerance); } [Fact] @@ -219,9 +250,9 @@ public void ToUnit() { var cubicmeterpersecond = VolumeFlow.FromCubicMetersPerSecond(1); - var centilitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentilitersPerMinute); - AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, (double)centilitersperminuteQuantity.Value, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentilitersPerMinute, centilitersperminuteQuantity.Unit); + var centiliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CentiliterPerMinute); + AssertEx.EqualTolerance(CentilitersPerMinuteInOneCubicMeterPerSecond, (double)centiliterperminuteQuantity.Value, CentilitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, centiliterperminuteQuantity.Unit); var cubicdecimeterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.CubicDecimeterPerMinute); AssertEx.EqualTolerance(CubicDecimetersPerMinuteInOneCubicMeterPerSecond, (double)cubicdecimeterperminuteQuantity.Value, CubicDecimetersPerMinuteTolerance); @@ -267,69 +298,69 @@ public void ToUnit() AssertEx.EqualTolerance(CubicYardsPerSecondInOneCubicMeterPerSecond, (double)cubicyardpersecondQuantity.Value, CubicYardsPerSecondTolerance); Assert.Equal(VolumeFlowUnit.CubicYardPerSecond, cubicyardpersecondQuantity.Unit); - var decilitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DecilitersPerMinute); - AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, (double)decilitersperminuteQuantity.Value, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecilitersPerMinute, decilitersperminuteQuantity.Unit); + var deciliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.DeciliterPerMinute); + AssertEx.EqualTolerance(DecilitersPerMinuteInOneCubicMeterPerSecond, (double)deciliterperminuteQuantity.Value, DecilitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, deciliterperminuteQuantity.Unit); - var kilolitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KilolitersPerMinute); - AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, (double)kilolitersperminuteQuantity.Value, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilolitersPerMinute, kilolitersperminuteQuantity.Unit); + var kiloliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KiloliterPerMinute); + AssertEx.EqualTolerance(KilolitersPerMinuteInOneCubicMeterPerSecond, (double)kiloliterperminuteQuantity.Value, KilolitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, kiloliterperminuteQuantity.Unit); var kilousgallonsperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.KilousGallonsPerMinute); AssertEx.EqualTolerance(KilousGallonsPerMinuteInOneCubicMeterPerSecond, (double)kilousgallonsperminuteQuantity.Value, KilousGallonsPerMinuteTolerance); Assert.Equal(VolumeFlowUnit.KilousGallonsPerMinute, kilousgallonsperminuteQuantity.Unit); - var litersperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LitersPerHour); - AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, (double)litersperhourQuantity.Value, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LitersPerHour, litersperhourQuantity.Unit); + var literperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerHour); + AssertEx.EqualTolerance(LitersPerHourInOneCubicMeterPerSecond, (double)literperhourQuantity.Value, LitersPerHourTolerance); + Assert.Equal(VolumeFlowUnit.LiterPerHour, literperhourQuantity.Unit); - var litersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LitersPerMinute); - AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, (double)litersperminuteQuantity.Value, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LitersPerMinute, litersperminuteQuantity.Unit); + var literperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerMinute); + AssertEx.EqualTolerance(LitersPerMinuteInOneCubicMeterPerSecond, (double)literperminuteQuantity.Value, LitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.LiterPerMinute, literperminuteQuantity.Unit); - var literspersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LitersPerSecond); - AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, (double)literspersecondQuantity.Value, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LitersPerSecond, literspersecondQuantity.Unit); + var literpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.LiterPerSecond); + AssertEx.EqualTolerance(LitersPerSecondInOneCubicMeterPerSecond, (double)literpersecondQuantity.Value, LitersPerSecondTolerance); + Assert.Equal(VolumeFlowUnit.LiterPerSecond, literpersecondQuantity.Unit); - var microlitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicrolitersPerMinute); - AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, (double)microlitersperminuteQuantity.Value, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicrolitersPerMinute, microlitersperminuteQuantity.Unit); + var microliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MicroliterPerMinute); + AssertEx.EqualTolerance(MicrolitersPerMinuteInOneCubicMeterPerSecond, (double)microliterperminuteQuantity.Value, MicrolitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, microliterperminuteQuantity.Unit); - var millilitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MillilitersPerMinute); - AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, (double)millilitersperminuteQuantity.Value, MillilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MillilitersPerMinute, millilitersperminuteQuantity.Unit); + var milliliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MilliliterPerMinute); + AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, (double)milliliterperminuteQuantity.Value, MillilitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, milliliterperminuteQuantity.Unit); var millionusgallonsperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.MillionUsGallonsPerDay); AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, (double)millionusgallonsperdayQuantity.Value, MillionUsGallonsPerDayTolerance); Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, millionusgallonsperdayQuantity.Unit); - var nanolitersperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanolitersPerMinute); - AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, (double)nanolitersperminuteQuantity.Value, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanolitersPerMinute, nanolitersperminuteQuantity.Unit); + var nanoliterperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.NanoliterPerMinute); + AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, (double)nanoliterperminuteQuantity.Value, NanolitersPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, nanoliterperminuteQuantity.Unit); - var oilbarrelsperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelsPerDay); - AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, (double)oilbarrelsperdayQuantity.Value, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelsPerDay, oilbarrelsperdayQuantity.Unit); + var oilbarrelperdayQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerDay); + AssertEx.EqualTolerance(OilBarrelsPerDayInOneCubicMeterPerSecond, (double)oilbarrelperdayQuantity.Value, OilBarrelsPerDayTolerance); + Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, oilbarrelperdayQuantity.Unit); - var oilbarrelsperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelsPerHour); - AssertEx.EqualTolerance(OilBarrelsPerHourInOneCubicMeterPerSecond, (double)oilbarrelsperhourQuantity.Value, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelsPerHour, oilbarrelsperhourQuantity.Unit); + var oilbarrelperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerHour); + AssertEx.EqualTolerance(OilBarrelsPerHourInOneCubicMeterPerSecond, (double)oilbarrelperhourQuantity.Value, OilBarrelsPerHourTolerance); + Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, oilbarrelperhourQuantity.Unit); - var oilbarrelsperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelsPerMinute); - AssertEx.EqualTolerance(OilBarrelsPerMinuteInOneCubicMeterPerSecond, (double)oilbarrelsperminuteQuantity.Value, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelsPerMinute, oilbarrelsperminuteQuantity.Unit); + var oilbarrelperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.OilBarrelPerMinute); + AssertEx.EqualTolerance(OilBarrelsPerMinuteInOneCubicMeterPerSecond, (double)oilbarrelperminuteQuantity.Value, OilBarrelsPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, oilbarrelperminuteQuantity.Unit); - var usgallonsperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonsPerHour); - AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, (double)usgallonsperhourQuantity.Value, UsGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonsPerHour, usgallonsperhourQuantity.Unit); + var usgallonperhourQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerHour); + AssertEx.EqualTolerance(UsGallonsPerHourInOneCubicMeterPerSecond, (double)usgallonperhourQuantity.Value, UsGallonsPerHourTolerance); + Assert.Equal(VolumeFlowUnit.UsGallonPerHour, usgallonperhourQuantity.Unit); - var usgallonsperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonsPerMinute); - AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, (double)usgallonsperminuteQuantity.Value, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonsPerMinute, usgallonsperminuteQuantity.Unit); + var usgallonperminuteQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerMinute); + AssertEx.EqualTolerance(UsGallonsPerMinuteInOneCubicMeterPerSecond, (double)usgallonperminuteQuantity.Value, UsGallonsPerMinuteTolerance); + Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, usgallonperminuteQuantity.Unit); - var usgallonspersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonsPerSecond); - AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, (double)usgallonspersecondQuantity.Value, UsGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonsPerSecond, usgallonspersecondQuantity.Unit); + var usgallonpersecondQuantity = cubicmeterpersecond.ToUnit(VolumeFlowUnit.UsGallonPerSecond); + AssertEx.EqualTolerance(UsGallonsPerSecondInOneCubicMeterPerSecond, (double)usgallonpersecondQuantity.Value, UsGallonsPerSecondTolerance); + Assert.Equal(VolumeFlowUnit.UsGallonPerSecond, usgallonpersecondQuantity.Unit); } [Fact] @@ -419,28 +450,43 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeterpersecond.CompareTo(null)); } - [Fact] public void EqualityOperators() { - VolumeFlow a = VolumeFlow.FromCubicMetersPerSecond(1); - VolumeFlow b = VolumeFlow.FromCubicMetersPerSecond(2); + var a = VolumeFlow.FromCubicMetersPerSecond(1); + var b = VolumeFlow.FromCubicMetersPerSecond(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - VolumeFlow v = VolumeFlow.FromCubicMetersPerSecond(1); - Assert.True(v.Equals(VolumeFlow.FromCubicMetersPerSecond(1), VolumeFlow.FromCubicMetersPerSecond(CubicMetersPerSecondTolerance))); - Assert.False(v.Equals(VolumeFlow.Zero, VolumeFlow.FromCubicMetersPerSecond(CubicMetersPerSecondTolerance))); + var a = VolumeFlow.FromCubicMetersPerSecond(1); + var b = VolumeFlow.FromCubicMetersPerSecond(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = VolumeFlow.FromCubicMetersPerSecond(1); + Assert.True(v.Equals(VolumeFlow.FromCubicMetersPerSecond(1), CubicMetersPerSecondTolerance, ComparisonType.Relative)); + Assert.False(v.Equals(VolumeFlow.Zero, CubicMetersPerSecondTolerance, ComparisonType.Relative)); } [Fact] @@ -463,5 +509,23 @@ 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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False(VolumeFlow.BaseDimensions is null); + } } } diff --git a/UnitsNet.Tests/GeneratedCode/VolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/VolumeTestsBase.g.cs deleted file mode 100644 index 155bca47f6..0000000000 --- a/UnitsNet.Tests/GeneratedCode/VolumeTestsBase.g.cs +++ /dev/null @@ -1,637 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Volume. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class VolumeTestsBase - { - protected abstract double AuTablespoonsInOneCubicMeter { get; } - protected abstract double CentilitersInOneCubicMeter { get; } - protected abstract double CubicCentimetersInOneCubicMeter { get; } - protected abstract double CubicDecimetersInOneCubicMeter { get; } - protected abstract double CubicFeetInOneCubicMeter { get; } - protected abstract double CubicInchesInOneCubicMeter { get; } - protected abstract double CubicKilometersInOneCubicMeter { get; } - protected abstract double CubicMetersInOneCubicMeter { get; } - protected abstract double CubicMicrometersInOneCubicMeter { get; } - protected abstract double CubicMilesInOneCubicMeter { get; } - protected abstract double CubicMillimetersInOneCubicMeter { get; } - protected abstract double CubicYardsInOneCubicMeter { get; } - protected abstract double DecilitersInOneCubicMeter { get; } - protected abstract double HectocubicFeetInOneCubicMeter { get; } - protected abstract double HectocubicMetersInOneCubicMeter { get; } - protected abstract double HectolitersInOneCubicMeter { get; } - protected abstract double ImperialBeerBarrelsInOneCubicMeter { get; } - protected abstract double ImperialGallonsInOneCubicMeter { get; } - protected abstract double ImperialOuncesInOneCubicMeter { get; } - protected abstract double KilocubicFeetInOneCubicMeter { get; } - protected abstract double KilocubicMetersInOneCubicMeter { get; } - protected abstract double KiloimperialGallonsInOneCubicMeter { get; } - protected abstract double KilolitersInOneCubicMeter { get; } - protected abstract double KilousGallonsInOneCubicMeter { get; } - protected abstract double LitersInOneCubicMeter { get; } - protected abstract double MegacubicFeetInOneCubicMeter { get; } - protected abstract double MegaimperialGallonsInOneCubicMeter { get; } - protected abstract double MegausGallonsInOneCubicMeter { get; } - protected abstract double MetricCupsInOneCubicMeter { get; } - protected abstract double MetricTeaspoonsInOneCubicMeter { get; } - protected abstract double MicrolitersInOneCubicMeter { get; } - protected abstract double MillilitersInOneCubicMeter { get; } - protected abstract double OilBarrelsInOneCubicMeter { get; } - protected abstract double TablespoonsInOneCubicMeter { get; } - protected abstract double TeaspoonsInOneCubicMeter { get; } - protected abstract double UkTablespoonsInOneCubicMeter { get; } - protected abstract double UsBeerBarrelsInOneCubicMeter { get; } - protected abstract double UsCustomaryCupsInOneCubicMeter { get; } - protected abstract double UsGallonsInOneCubicMeter { get; } - protected abstract double UsLegalCupsInOneCubicMeter { get; } - protected abstract double UsOuncesInOneCubicMeter { get; } - protected abstract double UsPintsInOneCubicMeter { get; } - protected abstract double UsQuartsInOneCubicMeter { get; } - protected abstract double UsTablespoonsInOneCubicMeter { get; } - protected abstract double UsTeaspoonsInOneCubicMeter { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AuTablespoonsTolerance { get { return 1e-5; } } - protected virtual double CentilitersTolerance { get { return 1e-5; } } - protected virtual double CubicCentimetersTolerance { get { return 1e-5; } } - protected virtual double CubicDecimetersTolerance { get { return 1e-5; } } - protected virtual double CubicFeetTolerance { get { return 1e-5; } } - protected virtual double CubicInchesTolerance { get { return 1e-5; } } - protected virtual double CubicKilometersTolerance { get { return 1e-5; } } - protected virtual double CubicMetersTolerance { get { return 1e-5; } } - protected virtual double CubicMicrometersTolerance { get { return 1e-5; } } - protected virtual double CubicMilesTolerance { get { return 1e-5; } } - protected virtual double CubicMillimetersTolerance { get { return 1e-5; } } - protected virtual double CubicYardsTolerance { get { return 1e-5; } } - protected virtual double DecilitersTolerance { get { return 1e-5; } } - protected virtual double HectocubicFeetTolerance { get { return 1e-5; } } - protected virtual double HectocubicMetersTolerance { get { return 1e-5; } } - protected virtual double HectolitersTolerance { get { return 1e-5; } } - protected virtual double ImperialBeerBarrelsTolerance { get { return 1e-5; } } - protected virtual double ImperialGallonsTolerance { get { return 1e-5; } } - protected virtual double ImperialOuncesTolerance { get { return 1e-5; } } - protected virtual double KilocubicFeetTolerance { get { return 1e-5; } } - protected virtual double KilocubicMetersTolerance { get { return 1e-5; } } - protected virtual double KiloimperialGallonsTolerance { get { return 1e-5; } } - protected virtual double KilolitersTolerance { get { return 1e-5; } } - protected virtual double KilousGallonsTolerance { get { return 1e-5; } } - protected virtual double LitersTolerance { get { return 1e-5; } } - protected virtual double MegacubicFeetTolerance { get { return 1e-5; } } - protected virtual double MegaimperialGallonsTolerance { get { return 1e-5; } } - protected virtual double MegausGallonsTolerance { get { return 1e-5; } } - protected virtual double MetricCupsTolerance { get { return 1e-5; } } - protected virtual double MetricTeaspoonsTolerance { get { return 1e-5; } } - protected virtual double MicrolitersTolerance { get { return 1e-5; } } - protected virtual double MillilitersTolerance { get { return 1e-5; } } - protected virtual double OilBarrelsTolerance { get { return 1e-5; } } - protected virtual double TablespoonsTolerance { get { return 1e-5; } } - protected virtual double TeaspoonsTolerance { get { return 1e-5; } } - protected virtual double UkTablespoonsTolerance { get { return 1e-5; } } - protected virtual double UsBeerBarrelsTolerance { get { return 1e-5; } } - protected virtual double UsCustomaryCupsTolerance { get { return 1e-5; } } - protected virtual double UsGallonsTolerance { get { return 1e-5; } } - protected virtual double UsLegalCupsTolerance { get { return 1e-5; } } - protected virtual double UsOuncesTolerance { get { return 1e-5; } } - protected virtual double UsPintsTolerance { get { return 1e-5; } } - protected virtual double UsQuartsTolerance { get { return 1e-5; } } - protected virtual double UsTablespoonsTolerance { get { return 1e-5; } } - protected virtual double UsTeaspoonsTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - [Fact] - public void CubicMeterToVolumeUnits() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(AuTablespoonsInOneCubicMeter, cubicmeter.AuTablespoons, AuTablespoonsTolerance); - AssertEx.EqualTolerance(CentilitersInOneCubicMeter, cubicmeter.Centiliters, CentilitersTolerance); - AssertEx.EqualTolerance(CubicCentimetersInOneCubicMeter, cubicmeter.CubicCentimeters, CubicCentimetersTolerance); - AssertEx.EqualTolerance(CubicDecimetersInOneCubicMeter, cubicmeter.CubicDecimeters, CubicDecimetersTolerance); - AssertEx.EqualTolerance(CubicFeetInOneCubicMeter, cubicmeter.CubicFeet, CubicFeetTolerance); - AssertEx.EqualTolerance(CubicInchesInOneCubicMeter, cubicmeter.CubicInches, CubicInchesTolerance); - AssertEx.EqualTolerance(CubicKilometersInOneCubicMeter, cubicmeter.CubicKilometers, CubicKilometersTolerance); - AssertEx.EqualTolerance(CubicMetersInOneCubicMeter, cubicmeter.CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(CubicMicrometersInOneCubicMeter, cubicmeter.CubicMicrometers, CubicMicrometersTolerance); - AssertEx.EqualTolerance(CubicMilesInOneCubicMeter, cubicmeter.CubicMiles, CubicMilesTolerance); - AssertEx.EqualTolerance(CubicMillimetersInOneCubicMeter, cubicmeter.CubicMillimeters, CubicMillimetersTolerance); - AssertEx.EqualTolerance(CubicYardsInOneCubicMeter, cubicmeter.CubicYards, CubicYardsTolerance); - AssertEx.EqualTolerance(DecilitersInOneCubicMeter, cubicmeter.Deciliters, DecilitersTolerance); - AssertEx.EqualTolerance(HectocubicFeetInOneCubicMeter, cubicmeter.HectocubicFeet, HectocubicFeetTolerance); - AssertEx.EqualTolerance(HectocubicMetersInOneCubicMeter, cubicmeter.HectocubicMeters, HectocubicMetersTolerance); - AssertEx.EqualTolerance(HectolitersInOneCubicMeter, cubicmeter.Hectoliters, HectolitersTolerance); - AssertEx.EqualTolerance(ImperialBeerBarrelsInOneCubicMeter, cubicmeter.ImperialBeerBarrels, ImperialBeerBarrelsTolerance); - AssertEx.EqualTolerance(ImperialGallonsInOneCubicMeter, cubicmeter.ImperialGallons, ImperialGallonsTolerance); - AssertEx.EqualTolerance(ImperialOuncesInOneCubicMeter, cubicmeter.ImperialOunces, ImperialOuncesTolerance); - AssertEx.EqualTolerance(KilocubicFeetInOneCubicMeter, cubicmeter.KilocubicFeet, KilocubicFeetTolerance); - AssertEx.EqualTolerance(KilocubicMetersInOneCubicMeter, cubicmeter.KilocubicMeters, KilocubicMetersTolerance); - AssertEx.EqualTolerance(KiloimperialGallonsInOneCubicMeter, cubicmeter.KiloimperialGallons, KiloimperialGallonsTolerance); - AssertEx.EqualTolerance(KilolitersInOneCubicMeter, cubicmeter.Kiloliters, KilolitersTolerance); - AssertEx.EqualTolerance(KilousGallonsInOneCubicMeter, cubicmeter.KilousGallons, KilousGallonsTolerance); - AssertEx.EqualTolerance(LitersInOneCubicMeter, cubicmeter.Liters, LitersTolerance); - AssertEx.EqualTolerance(MegacubicFeetInOneCubicMeter, cubicmeter.MegacubicFeet, MegacubicFeetTolerance); - AssertEx.EqualTolerance(MegaimperialGallonsInOneCubicMeter, cubicmeter.MegaimperialGallons, MegaimperialGallonsTolerance); - AssertEx.EqualTolerance(MegausGallonsInOneCubicMeter, cubicmeter.MegausGallons, MegausGallonsTolerance); - AssertEx.EqualTolerance(MetricCupsInOneCubicMeter, cubicmeter.MetricCups, MetricCupsTolerance); - AssertEx.EqualTolerance(MetricTeaspoonsInOneCubicMeter, cubicmeter.MetricTeaspoons, MetricTeaspoonsTolerance); - AssertEx.EqualTolerance(MicrolitersInOneCubicMeter, cubicmeter.Microliters, MicrolitersTolerance); - AssertEx.EqualTolerance(MillilitersInOneCubicMeter, cubicmeter.Milliliters, MillilitersTolerance); - AssertEx.EqualTolerance(OilBarrelsInOneCubicMeter, cubicmeter.OilBarrels, OilBarrelsTolerance); - AssertEx.EqualTolerance(TablespoonsInOneCubicMeter, cubicmeter.Tablespoons, TablespoonsTolerance); - AssertEx.EqualTolerance(TeaspoonsInOneCubicMeter, cubicmeter.Teaspoons, TeaspoonsTolerance); - AssertEx.EqualTolerance(UkTablespoonsInOneCubicMeter, cubicmeter.UkTablespoons, UkTablespoonsTolerance); - AssertEx.EqualTolerance(UsBeerBarrelsInOneCubicMeter, cubicmeter.UsBeerBarrels, UsBeerBarrelsTolerance); - AssertEx.EqualTolerance(UsCustomaryCupsInOneCubicMeter, cubicmeter.UsCustomaryCups, UsCustomaryCupsTolerance); - AssertEx.EqualTolerance(UsGallonsInOneCubicMeter, cubicmeter.UsGallons, UsGallonsTolerance); - AssertEx.EqualTolerance(UsLegalCupsInOneCubicMeter, cubicmeter.UsLegalCups, UsLegalCupsTolerance); - AssertEx.EqualTolerance(UsOuncesInOneCubicMeter, cubicmeter.UsOunces, UsOuncesTolerance); - AssertEx.EqualTolerance(UsPintsInOneCubicMeter, cubicmeter.UsPints, UsPintsTolerance); - AssertEx.EqualTolerance(UsQuartsInOneCubicMeter, cubicmeter.UsQuarts, UsQuartsTolerance); - AssertEx.EqualTolerance(UsTablespoonsInOneCubicMeter, cubicmeter.UsTablespoons, UsTablespoonsTolerance); - AssertEx.EqualTolerance(UsTeaspoonsInOneCubicMeter, cubicmeter.UsTeaspoons, UsTeaspoonsTolerance); - } - - [Fact] - public void FromValueAndUnit() - { - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.AuTablespoon).AuTablespoons, AuTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Centiliter).Centiliters, CentilitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicCentimeter).CubicCentimeters, CubicCentimetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicDecimeter).CubicDecimeters, CubicDecimetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicFoot).CubicFeet, CubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicInch).CubicInches, CubicInchesTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicKilometer).CubicKilometers, CubicKilometersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicMeter).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicMicrometer).CubicMicrometers, CubicMicrometersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicMile).CubicMiles, CubicMilesTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicMillimeter).CubicMillimeters, CubicMillimetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.CubicYard).CubicYards, CubicYardsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Deciliter).Deciliters, DecilitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.HectocubicFoot).HectocubicFeet, HectocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.HectocubicMeter).HectocubicMeters, HectocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Hectoliter).Hectoliters, HectolitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.ImperialBeerBarrel).ImperialBeerBarrels, ImperialBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.ImperialGallon).ImperialGallons, ImperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.ImperialOunce).ImperialOunces, ImperialOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.KilocubicFoot).KilocubicFeet, KilocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.KilocubicMeter).KilocubicMeters, KilocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.KiloimperialGallon).KiloimperialGallons, KiloimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Kiloliter).Kiloliters, KilolitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.KilousGallon).KilousGallons, KilousGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Liter).Liters, LitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.MegacubicFoot).MegacubicFeet, MegacubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.MegaimperialGallon).MegaimperialGallons, MegaimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.MegausGallon).MegausGallons, MegausGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.MetricCup).MetricCups, MetricCupsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.MetricTeaspoon).MetricTeaspoons, MetricTeaspoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Microliter).Microliters, MicrolitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Milliliter).Milliliters, MillilitersTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.OilBarrel).OilBarrels, OilBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Tablespoon).Tablespoons, TablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.Teaspoon).Teaspoons, TeaspoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UkTablespoon).UkTablespoons, UkTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsBeerBarrel).UsBeerBarrels, UsBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsCustomaryCup).UsCustomaryCups, UsCustomaryCupsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsGallon).UsGallons, UsGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsLegalCup).UsLegalCups, UsLegalCupsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsOunce).UsOunces, UsOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsPint).UsPints, UsPintsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsQuart).UsQuarts, UsQuartsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsTablespoon).UsTablespoons, UsTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.From(1, VolumeUnit.UsTeaspoon).UsTeaspoons, UsTeaspoonsTolerance); - } - - [Fact] - public void As() - { - var cubicmeter = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(AuTablespoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.AuTablespoon), AuTablespoonsTolerance); - AssertEx.EqualTolerance(CentilitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Centiliter), CentilitersTolerance); - AssertEx.EqualTolerance(CubicCentimetersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicCentimeter), CubicCentimetersTolerance); - AssertEx.EqualTolerance(CubicDecimetersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicDecimeter), CubicDecimetersTolerance); - AssertEx.EqualTolerance(CubicFeetInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicFoot), CubicFeetTolerance); - AssertEx.EqualTolerance(CubicInchesInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicInch), CubicInchesTolerance); - AssertEx.EqualTolerance(CubicKilometersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicKilometer), CubicKilometersTolerance); - AssertEx.EqualTolerance(CubicMetersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicMeter), CubicMetersTolerance); - AssertEx.EqualTolerance(CubicMicrometersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicMicrometer), CubicMicrometersTolerance); - AssertEx.EqualTolerance(CubicMilesInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicMile), CubicMilesTolerance); - AssertEx.EqualTolerance(CubicMillimetersInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicMillimeter), CubicMillimetersTolerance); - AssertEx.EqualTolerance(CubicYardsInOneCubicMeter, cubicmeter.As(VolumeUnit.CubicYard), CubicYardsTolerance); - AssertEx.EqualTolerance(DecilitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Deciliter), DecilitersTolerance); - AssertEx.EqualTolerance(HectocubicFeetInOneCubicMeter, cubicmeter.As(VolumeUnit.HectocubicFoot), HectocubicFeetTolerance); - AssertEx.EqualTolerance(HectocubicMetersInOneCubicMeter, cubicmeter.As(VolumeUnit.HectocubicMeter), HectocubicMetersTolerance); - AssertEx.EqualTolerance(HectolitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Hectoliter), HectolitersTolerance); - AssertEx.EqualTolerance(ImperialBeerBarrelsInOneCubicMeter, cubicmeter.As(VolumeUnit.ImperialBeerBarrel), ImperialBeerBarrelsTolerance); - AssertEx.EqualTolerance(ImperialGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.ImperialGallon), ImperialGallonsTolerance); - AssertEx.EqualTolerance(ImperialOuncesInOneCubicMeter, cubicmeter.As(VolumeUnit.ImperialOunce), ImperialOuncesTolerance); - AssertEx.EqualTolerance(KilocubicFeetInOneCubicMeter, cubicmeter.As(VolumeUnit.KilocubicFoot), KilocubicFeetTolerance); - AssertEx.EqualTolerance(KilocubicMetersInOneCubicMeter, cubicmeter.As(VolumeUnit.KilocubicMeter), KilocubicMetersTolerance); - AssertEx.EqualTolerance(KiloimperialGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.KiloimperialGallon), KiloimperialGallonsTolerance); - AssertEx.EqualTolerance(KilolitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Kiloliter), KilolitersTolerance); - AssertEx.EqualTolerance(KilousGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.KilousGallon), KilousGallonsTolerance); - AssertEx.EqualTolerance(LitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Liter), LitersTolerance); - AssertEx.EqualTolerance(MegacubicFeetInOneCubicMeter, cubicmeter.As(VolumeUnit.MegacubicFoot), MegacubicFeetTolerance); - AssertEx.EqualTolerance(MegaimperialGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.MegaimperialGallon), MegaimperialGallonsTolerance); - AssertEx.EqualTolerance(MegausGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.MegausGallon), MegausGallonsTolerance); - AssertEx.EqualTolerance(MetricCupsInOneCubicMeter, cubicmeter.As(VolumeUnit.MetricCup), MetricCupsTolerance); - AssertEx.EqualTolerance(MetricTeaspoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.MetricTeaspoon), MetricTeaspoonsTolerance); - AssertEx.EqualTolerance(MicrolitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Microliter), MicrolitersTolerance); - AssertEx.EqualTolerance(MillilitersInOneCubicMeter, cubicmeter.As(VolumeUnit.Milliliter), MillilitersTolerance); - AssertEx.EqualTolerance(OilBarrelsInOneCubicMeter, cubicmeter.As(VolumeUnit.OilBarrel), OilBarrelsTolerance); - AssertEx.EqualTolerance(TablespoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.Tablespoon), TablespoonsTolerance); - AssertEx.EqualTolerance(TeaspoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.Teaspoon), TeaspoonsTolerance); - AssertEx.EqualTolerance(UkTablespoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.UkTablespoon), UkTablespoonsTolerance); - AssertEx.EqualTolerance(UsBeerBarrelsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsBeerBarrel), UsBeerBarrelsTolerance); - AssertEx.EqualTolerance(UsCustomaryCupsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsCustomaryCup), UsCustomaryCupsTolerance); - AssertEx.EqualTolerance(UsGallonsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsGallon), UsGallonsTolerance); - AssertEx.EqualTolerance(UsLegalCupsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsLegalCup), UsLegalCupsTolerance); - AssertEx.EqualTolerance(UsOuncesInOneCubicMeter, cubicmeter.As(VolumeUnit.UsOunce), UsOuncesTolerance); - AssertEx.EqualTolerance(UsPintsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsPint), UsPintsTolerance); - AssertEx.EqualTolerance(UsQuartsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsQuart), UsQuartsTolerance); - AssertEx.EqualTolerance(UsTablespoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsTablespoon), UsTablespoonsTolerance); - AssertEx.EqualTolerance(UsTeaspoonsInOneCubicMeter, cubicmeter.As(VolumeUnit.UsTeaspoon), UsTeaspoonsTolerance); - } - - [Fact] - public void ToUnit() - { - var cubicmeter = Volume.FromCubicMeters(1); - - var autablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.AuTablespoon); - AssertEx.EqualTolerance(AuTablespoonsInOneCubicMeter, (double)autablespoonQuantity.Value, AuTablespoonsTolerance); - Assert.Equal(VolumeUnit.AuTablespoon, autablespoonQuantity.Unit); - - var centiliterQuantity = cubicmeter.ToUnit(VolumeUnit.Centiliter); - AssertEx.EqualTolerance(CentilitersInOneCubicMeter, (double)centiliterQuantity.Value, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, centiliterQuantity.Unit); - - var cubiccentimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicCentimeter); - AssertEx.EqualTolerance(CubicCentimetersInOneCubicMeter, (double)cubiccentimeterQuantity.Value, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, cubiccentimeterQuantity.Unit); - - var cubicdecimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicDecimeter); - AssertEx.EqualTolerance(CubicDecimetersInOneCubicMeter, (double)cubicdecimeterQuantity.Value, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, cubicdecimeterQuantity.Unit); - - var cubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.CubicFoot); - AssertEx.EqualTolerance(CubicFeetInOneCubicMeter, (double)cubicfootQuantity.Value, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, cubicfootQuantity.Unit); - - var cubicinchQuantity = cubicmeter.ToUnit(VolumeUnit.CubicInch); - AssertEx.EqualTolerance(CubicInchesInOneCubicMeter, (double)cubicinchQuantity.Value, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, cubicinchQuantity.Unit); - - var cubickilometerQuantity = cubicmeter.ToUnit(VolumeUnit.CubicKilometer); - AssertEx.EqualTolerance(CubicKilometersInOneCubicMeter, (double)cubickilometerQuantity.Value, CubicKilometersTolerance); - Assert.Equal(VolumeUnit.CubicKilometer, cubickilometerQuantity.Unit); - - var cubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMeter); - AssertEx.EqualTolerance(CubicMetersInOneCubicMeter, (double)cubicmeterQuantity.Value, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, cubicmeterQuantity.Unit); - - var cubicmicrometerQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMicrometer); - AssertEx.EqualTolerance(CubicMicrometersInOneCubicMeter, (double)cubicmicrometerQuantity.Value, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, cubicmicrometerQuantity.Unit); - - var cubicmileQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMile); - AssertEx.EqualTolerance(CubicMilesInOneCubicMeter, (double)cubicmileQuantity.Value, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, cubicmileQuantity.Unit); - - var cubicmillimeterQuantity = cubicmeter.ToUnit(VolumeUnit.CubicMillimeter); - AssertEx.EqualTolerance(CubicMillimetersInOneCubicMeter, (double)cubicmillimeterQuantity.Value, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, cubicmillimeterQuantity.Unit); - - var cubicyardQuantity = cubicmeter.ToUnit(VolumeUnit.CubicYard); - AssertEx.EqualTolerance(CubicYardsInOneCubicMeter, (double)cubicyardQuantity.Value, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, cubicyardQuantity.Unit); - - var deciliterQuantity = cubicmeter.ToUnit(VolumeUnit.Deciliter); - AssertEx.EqualTolerance(DecilitersInOneCubicMeter, (double)deciliterQuantity.Value, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, deciliterQuantity.Unit); - - var hectocubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.HectocubicFoot); - AssertEx.EqualTolerance(HectocubicFeetInOneCubicMeter, (double)hectocubicfootQuantity.Value, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, hectocubicfootQuantity.Unit); - - var hectocubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.HectocubicMeter); - AssertEx.EqualTolerance(HectocubicMetersInOneCubicMeter, (double)hectocubicmeterQuantity.Value, HectocubicMetersTolerance); - Assert.Equal(VolumeUnit.HectocubicMeter, hectocubicmeterQuantity.Unit); - - var hectoliterQuantity = cubicmeter.ToUnit(VolumeUnit.Hectoliter); - AssertEx.EqualTolerance(HectolitersInOneCubicMeter, (double)hectoliterQuantity.Value, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, hectoliterQuantity.Unit); - - var imperialbeerbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialBeerBarrel); - AssertEx.EqualTolerance(ImperialBeerBarrelsInOneCubicMeter, (double)imperialbeerbarrelQuantity.Value, ImperialBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.ImperialBeerBarrel, imperialbeerbarrelQuantity.Unit); - - var imperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialGallon); - AssertEx.EqualTolerance(ImperialGallonsInOneCubicMeter, (double)imperialgallonQuantity.Value, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, imperialgallonQuantity.Unit); - - var imperialounceQuantity = cubicmeter.ToUnit(VolumeUnit.ImperialOunce); - AssertEx.EqualTolerance(ImperialOuncesInOneCubicMeter, (double)imperialounceQuantity.Value, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, imperialounceQuantity.Unit); - - var kilocubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.KilocubicFoot); - AssertEx.EqualTolerance(KilocubicFeetInOneCubicMeter, (double)kilocubicfootQuantity.Value, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, kilocubicfootQuantity.Unit); - - var kilocubicmeterQuantity = cubicmeter.ToUnit(VolumeUnit.KilocubicMeter); - AssertEx.EqualTolerance(KilocubicMetersInOneCubicMeter, (double)kilocubicmeterQuantity.Value, KilocubicMetersTolerance); - Assert.Equal(VolumeUnit.KilocubicMeter, kilocubicmeterQuantity.Unit); - - var kiloimperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.KiloimperialGallon); - AssertEx.EqualTolerance(KiloimperialGallonsInOneCubicMeter, (double)kiloimperialgallonQuantity.Value, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, kiloimperialgallonQuantity.Unit); - - var kiloliterQuantity = cubicmeter.ToUnit(VolumeUnit.Kiloliter); - AssertEx.EqualTolerance(KilolitersInOneCubicMeter, (double)kiloliterQuantity.Value, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, kiloliterQuantity.Unit); - - var kilousgallonQuantity = cubicmeter.ToUnit(VolumeUnit.KilousGallon); - AssertEx.EqualTolerance(KilousGallonsInOneCubicMeter, (double)kilousgallonQuantity.Value, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, kilousgallonQuantity.Unit); - - var literQuantity = cubicmeter.ToUnit(VolumeUnit.Liter); - AssertEx.EqualTolerance(LitersInOneCubicMeter, (double)literQuantity.Value, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, literQuantity.Unit); - - var megacubicfootQuantity = cubicmeter.ToUnit(VolumeUnit.MegacubicFoot); - AssertEx.EqualTolerance(MegacubicFeetInOneCubicMeter, (double)megacubicfootQuantity.Value, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, megacubicfootQuantity.Unit); - - var megaimperialgallonQuantity = cubicmeter.ToUnit(VolumeUnit.MegaimperialGallon); - AssertEx.EqualTolerance(MegaimperialGallonsInOneCubicMeter, (double)megaimperialgallonQuantity.Value, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, megaimperialgallonQuantity.Unit); - - var megausgallonQuantity = cubicmeter.ToUnit(VolumeUnit.MegausGallon); - AssertEx.EqualTolerance(MegausGallonsInOneCubicMeter, (double)megausgallonQuantity.Value, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, megausgallonQuantity.Unit); - - var metriccupQuantity = cubicmeter.ToUnit(VolumeUnit.MetricCup); - AssertEx.EqualTolerance(MetricCupsInOneCubicMeter, (double)metriccupQuantity.Value, MetricCupsTolerance); - Assert.Equal(VolumeUnit.MetricCup, metriccupQuantity.Unit); - - var metricteaspoonQuantity = cubicmeter.ToUnit(VolumeUnit.MetricTeaspoon); - AssertEx.EqualTolerance(MetricTeaspoonsInOneCubicMeter, (double)metricteaspoonQuantity.Value, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, metricteaspoonQuantity.Unit); - - var microliterQuantity = cubicmeter.ToUnit(VolumeUnit.Microliter); - AssertEx.EqualTolerance(MicrolitersInOneCubicMeter, (double)microliterQuantity.Value, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, microliterQuantity.Unit); - - var milliliterQuantity = cubicmeter.ToUnit(VolumeUnit.Milliliter); - AssertEx.EqualTolerance(MillilitersInOneCubicMeter, (double)milliliterQuantity.Value, MillilitersTolerance); - Assert.Equal(VolumeUnit.Milliliter, milliliterQuantity.Unit); - - var oilbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.OilBarrel); - AssertEx.EqualTolerance(OilBarrelsInOneCubicMeter, (double)oilbarrelQuantity.Value, OilBarrelsTolerance); - Assert.Equal(VolumeUnit.OilBarrel, oilbarrelQuantity.Unit); - - var tablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.Tablespoon); - AssertEx.EqualTolerance(TablespoonsInOneCubicMeter, (double)tablespoonQuantity.Value, TablespoonsTolerance); - Assert.Equal(VolumeUnit.Tablespoon, tablespoonQuantity.Unit); - - var teaspoonQuantity = cubicmeter.ToUnit(VolumeUnit.Teaspoon); - AssertEx.EqualTolerance(TeaspoonsInOneCubicMeter, (double)teaspoonQuantity.Value, TeaspoonsTolerance); - Assert.Equal(VolumeUnit.Teaspoon, teaspoonQuantity.Unit); - - var uktablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.UkTablespoon); - AssertEx.EqualTolerance(UkTablespoonsInOneCubicMeter, (double)uktablespoonQuantity.Value, UkTablespoonsTolerance); - Assert.Equal(VolumeUnit.UkTablespoon, uktablespoonQuantity.Unit); - - var usbeerbarrelQuantity = cubicmeter.ToUnit(VolumeUnit.UsBeerBarrel); - AssertEx.EqualTolerance(UsBeerBarrelsInOneCubicMeter, (double)usbeerbarrelQuantity.Value, UsBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.UsBeerBarrel, usbeerbarrelQuantity.Unit); - - var uscustomarycupQuantity = cubicmeter.ToUnit(VolumeUnit.UsCustomaryCup); - AssertEx.EqualTolerance(UsCustomaryCupsInOneCubicMeter, (double)uscustomarycupQuantity.Value, UsCustomaryCupsTolerance); - Assert.Equal(VolumeUnit.UsCustomaryCup, uscustomarycupQuantity.Unit); - - var usgallonQuantity = cubicmeter.ToUnit(VolumeUnit.UsGallon); - AssertEx.EqualTolerance(UsGallonsInOneCubicMeter, (double)usgallonQuantity.Value, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, usgallonQuantity.Unit); - - var uslegalcupQuantity = cubicmeter.ToUnit(VolumeUnit.UsLegalCup); - AssertEx.EqualTolerance(UsLegalCupsInOneCubicMeter, (double)uslegalcupQuantity.Value, UsLegalCupsTolerance); - Assert.Equal(VolumeUnit.UsLegalCup, uslegalcupQuantity.Unit); - - var usounceQuantity = cubicmeter.ToUnit(VolumeUnit.UsOunce); - AssertEx.EqualTolerance(UsOuncesInOneCubicMeter, (double)usounceQuantity.Value, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, usounceQuantity.Unit); - - var uspintQuantity = cubicmeter.ToUnit(VolumeUnit.UsPint); - AssertEx.EqualTolerance(UsPintsInOneCubicMeter, (double)uspintQuantity.Value, UsPintsTolerance); - Assert.Equal(VolumeUnit.UsPint, uspintQuantity.Unit); - - var usquartQuantity = cubicmeter.ToUnit(VolumeUnit.UsQuart); - AssertEx.EqualTolerance(UsQuartsInOneCubicMeter, (double)usquartQuantity.Value, UsQuartsTolerance); - Assert.Equal(VolumeUnit.UsQuart, usquartQuantity.Unit); - - var ustablespoonQuantity = cubicmeter.ToUnit(VolumeUnit.UsTablespoon); - AssertEx.EqualTolerance(UsTablespoonsInOneCubicMeter, (double)ustablespoonQuantity.Value, UsTablespoonsTolerance); - Assert.Equal(VolumeUnit.UsTablespoon, ustablespoonQuantity.Unit); - - var usteaspoonQuantity = cubicmeter.ToUnit(VolumeUnit.UsTeaspoon); - AssertEx.EqualTolerance(UsTeaspoonsInOneCubicMeter, (double)usteaspoonQuantity.Value, UsTeaspoonsTolerance); - Assert.Equal(VolumeUnit.UsTeaspoon, usteaspoonQuantity.Unit); - } - - [Fact] - public void ConversionRoundTrip() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(1, Volume.FromAuTablespoons(cubicmeter.AuTablespoons).CubicMeters, AuTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromCentiliters(cubicmeter.Centiliters).CubicMeters, CentilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicCentimeters(cubicmeter.CubicCentimeters).CubicMeters, CubicCentimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicDecimeters(cubicmeter.CubicDecimeters).CubicMeters, CubicDecimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicFeet(cubicmeter.CubicFeet).CubicMeters, CubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicInches(cubicmeter.CubicInches).CubicMeters, CubicInchesTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicKilometers(cubicmeter.CubicKilometers).CubicMeters, CubicKilometersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMeters(cubicmeter.CubicMeters).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMicrometers(cubicmeter.CubicMicrometers).CubicMeters, CubicMicrometersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMiles(cubicmeter.CubicMiles).CubicMeters, CubicMilesTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMillimeters(cubicmeter.CubicMillimeters).CubicMeters, CubicMillimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicYards(cubicmeter.CubicYards).CubicMeters, CubicYardsTolerance); - AssertEx.EqualTolerance(1, Volume.FromDeciliters(cubicmeter.Deciliters).CubicMeters, DecilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectocubicFeet(cubicmeter.HectocubicFeet).CubicMeters, HectocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectocubicMeters(cubicmeter.HectocubicMeters).CubicMeters, HectocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectoliters(cubicmeter.Hectoliters).CubicMeters, HectolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialBeerBarrels(cubicmeter.ImperialBeerBarrels).CubicMeters, ImperialBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialGallons(cubicmeter.ImperialGallons).CubicMeters, ImperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialOunces(cubicmeter.ImperialOunces).CubicMeters, ImperialOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilocubicFeet(cubicmeter.KilocubicFeet).CubicMeters, KilocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilocubicMeters(cubicmeter.KilocubicMeters).CubicMeters, KilocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromKiloimperialGallons(cubicmeter.KiloimperialGallons).CubicMeters, KiloimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromKiloliters(cubicmeter.Kiloliters).CubicMeters, KilolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilousGallons(cubicmeter.KilousGallons).CubicMeters, KilousGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromLiters(cubicmeter.Liters).CubicMeters, LitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegacubicFeet(cubicmeter.MegacubicFeet).CubicMeters, MegacubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegaimperialGallons(cubicmeter.MegaimperialGallons).CubicMeters, MegaimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegausGallons(cubicmeter.MegausGallons).CubicMeters, MegausGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMetricCups(cubicmeter.MetricCups).CubicMeters, MetricCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMetricTeaspoons(cubicmeter.MetricTeaspoons).CubicMeters, MetricTeaspoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMicroliters(cubicmeter.Microliters).CubicMeters, MicrolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromMilliliters(cubicmeter.Milliliters).CubicMeters, MillilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromOilBarrels(cubicmeter.OilBarrels).CubicMeters, OilBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromTablespoons(cubicmeter.Tablespoons).CubicMeters, TablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromTeaspoons(cubicmeter.Teaspoons).CubicMeters, TeaspoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUkTablespoons(cubicmeter.UkTablespoons).CubicMeters, UkTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsBeerBarrels(cubicmeter.UsBeerBarrels).CubicMeters, UsBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsCustomaryCups(cubicmeter.UsCustomaryCups).CubicMeters, UsCustomaryCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsGallons(cubicmeter.UsGallons).CubicMeters, UsGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsLegalCups(cubicmeter.UsLegalCups).CubicMeters, UsLegalCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsOunces(cubicmeter.UsOunces).CubicMeters, UsOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsPints(cubicmeter.UsPints).CubicMeters, UsPintsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsQuarts(cubicmeter.UsQuarts).CubicMeters, UsQuartsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsTablespoons(cubicmeter.UsTablespoons).CubicMeters, UsTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsTeaspoons(cubicmeter.UsTeaspoons).CubicMeters, UsTeaspoonsTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Volume v = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(-1, -v.CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (Volume.FromCubicMeters(3)-v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (Volume.FromCubicMeters(10)/5).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, Volume.FromCubicMeters(10)/Volume.FromCubicMeters(5), CubicMetersTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Volume oneCubicMeter = Volume.FromCubicMeters(1); - Volume twoCubicMeters = Volume.FromCubicMeters(2); - - Assert.True(oneCubicMeter < twoCubicMeters); - Assert.True(oneCubicMeter <= twoCubicMeters); - Assert.True(twoCubicMeters > oneCubicMeter); - Assert.True(twoCubicMeters >= oneCubicMeter); - - Assert.False(oneCubicMeter > twoCubicMeters); - Assert.False(oneCubicMeter >= twoCubicMeters); - Assert.False(twoCubicMeters < oneCubicMeter); - Assert.False(twoCubicMeters <= oneCubicMeter); - } - - [Fact] - public void CompareToIsImplemented() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - Assert.Equal(0, cubicmeter.CompareTo(cubicmeter)); - Assert.True(cubicmeter.CompareTo(Volume.Zero) > 0); - Assert.True(Volume.Zero.CompareTo(cubicmeter) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - Assert.Throws(() => cubicmeter.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - Assert.Throws(() => cubicmeter.CompareTo(null)); - } - - - [Fact] - public void EqualityOperators() - { - Volume a = Volume.FromCubicMeters(1); - Volume b = Volume.FromCubicMeters(2); - -// ReSharper disable EqualExpressionComparison - Assert.True(a == a); - Assert.True(a != b); - - Assert.False(a == b); - Assert.False(a != a); -// ReSharper restore EqualExpressionComparison - } - - [Fact] - public void EqualsIsImplemented() - { - Volume v = Volume.FromCubicMeters(1); - Assert.True(v.Equals(Volume.FromCubicMeters(1), Volume.FromCubicMeters(CubicMetersTolerance))); - Assert.False(v.Equals(Volume.Zero, Volume.FromCubicMeters(CubicMetersTolerance))); - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - Assert.False(cubicmeter.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Volume cubicmeter = Volume.FromCubicMeters(1); - Assert.False(cubicmeter.Equals(null)); - } - - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumeUnit.Undefined, Volume.Units); - } - - } -} diff --git a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs index 501c0c5675..4f188897f4 100644 --- a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs +++ b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs @@ -18,14 +18,15 @@ public class QuantitiesWithDouble [Fact] public void LengthEquals_GivenMaxError_ReturnsTrueIfWithinError() { - Length smallError = Length.FromMeters(1e-5); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), Length.Zero), "Integer values have zero difference."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError), "Using a max difference value should not change that fact."); + var smallError = 1e-5; - Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), Length.Zero), + Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), 0, ComparisonType.Relative), "Integer values have zero difference."); + Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), "Using a max difference value should not change that fact."); + + Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0, ComparisonType.Relative), "Example of floating precision arithmetic that produces slightly different results."); - Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError), "But the difference is very small"); + Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), "But the difference is very small"); } } } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/IntOverloadTests.cs b/UnitsNet.Tests/IntOverloadTests.cs index 3a762ecb54..c1aa279748 100644 --- a/UnitsNet.Tests/IntOverloadTests.cs +++ b/UnitsNet.Tests/IntOverloadTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,8 +20,6 @@ // THE SOFTWARE. using Xunit; -using UnitsNet.Extensions.NumberToAcceleration; -using UnitsNet.Extensions.NumberToPower; namespace UnitsNet.Tests { @@ -30,101 +28,15 @@ public class IntOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromIntReturnsCorrectValue() { - int oneMeterPerSecondSquared = 1; - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableIntReturnsCorrectValue() - { - int? oneMeterPerSecondSquared = 1; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableIntReturnsNullWhenGivenNull() - { - int? nullInt = null; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(nullInt); - Assert.Null(acceleration); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromIntWithExtensionMethodReturnsCorrectValue() - { - int oneMeterPerSecondSquared = 1; - Acceleration acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.Equal(1.0, acceleration.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableIntWithExtensionMethodReturnsCorrectValue() - { - int? oneMeterPerSecondSquared = 1; - Acceleration? acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableIntWithExtensionMethodReturnsNullWhenGivenNull() - { - int? nullInt = null; - Acceleration? acceleration = nullInt.MetersPerSecondSquared(); - Assert.Null(acceleration); - } - [Fact] public static void CreatingQuantityWithIntBackingFieldFromIntReturnsCorrectValue() { - int oneWatt = 1; - Power power = Power.FromWatts(oneWatt); + Power power = Power.FromWatts(1); Assert.Equal(1.0, power.Watts); } - - [Fact] - public static void CreatingQuantityWithIntBackingFieldFromNullableIntReturnsCorrectValue() - { - int? oneWatt = 1; - Power? power = Power.FromWatts(oneWatt); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithIntBackingFieldFromNullableIntReturnsNullWhenGivenNull() - { - int? nullInt = null; - Power? power = Power.FromWatts(nullInt); - Assert.Null(power); - } - - [Fact] - public static void CreatingQuantityWithIntBackingFieldFromIntWithExtensionMethodReturnsCorrectValue() - { - int oneWatt = 1; - Power power = oneWatt.Watts(); - Assert.Equal(1.0, power.Watts); - } - - [Fact] - public static void CreatingQuantityWithIntBackingFieldFromNullableIntWithExtensionMethodReturnsCorrectValue() - { - int? oneWatt = 1; - Power? power = oneWatt.Watts(); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithIntBackingFieldFromNullableIntWithExtensionMethodReturnsNullWhenGivenNull() - { - int? nullInt = null; - Power? power = nullInt.Watts(); - Assert.Null(power); - } } } diff --git a/UnitsNet.Tests/LongOverloadTests.cs b/UnitsNet.Tests/LongOverloadTests.cs index d64ee9fa03..2423091f72 100644 --- a/UnitsNet.Tests/LongOverloadTests.cs +++ b/UnitsNet.Tests/LongOverloadTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,8 +20,6 @@ // THE SOFTWARE. using Xunit; -using UnitsNet.Extensions.NumberToAcceleration; -using UnitsNet.Extensions.NumberToPower; namespace UnitsNet.Tests { @@ -30,101 +28,15 @@ public class LongOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromLongReturnsCorrectValue() { - long oneMeterPerSecondSquared = 1; - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1L); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableLongReturnsCorrectValue() - { - long? oneMeterPerSecondSquared = 1; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(oneMeterPerSecondSquared); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableLongReturnsNullWhenGivenNull() - { - long? nullLong = null; - Acceleration? acceleration = Acceleration.FromMetersPerSecondSquared(nullLong); - Assert.Null(acceleration); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromLongWithExtensionMethodReturnsCorrectValue() - { - long oneMeterPerSecondSquared = 1; - Acceleration acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.Equal(1.0, acceleration.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableLongWithExtensionMethodReturnsCorrectValue() - { - long? oneMeterPerSecondSquared = 1; - Acceleration? acceleration = oneMeterPerSecondSquared.MetersPerSecondSquared(); - Assert.NotNull(acceleration); - Assert.Equal(1.0, acceleration.Value.MetersPerSecondSquared); - } - - [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromNullableLongWithExtensionMethodReturnsNullWhenGivenNull() - { - long? nullLong = null; - Acceleration? acceleration = nullLong.MetersPerSecondSquared(); - Assert.Null(acceleration); - } - [Fact] public static void CreatingQuantityWithLongBackingFieldFromLongReturnsCorrectValue() { - long oneWatt = 1; - Power power = Power.FromWatts(oneWatt); + Power power = Power.FromWatts(1L); Assert.Equal(1.0, power.Watts); } - - [Fact] - public static void CreatingQuantityWithLongBackingFieldFromNullableLongReturnsCorrectValue() - { - long? oneWatt = 1; - Power? power = Power.FromWatts(oneWatt); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithLongBackingFieldFromNullableLongReturnsNullWhenGivenNull() - { - long? nullLong = null; - Power? power = Power.FromWatts(nullLong); - Assert.Null(power); - } - - [Fact] - public static void CreatingQuantityWithLongBackingFieldFromLongWithExtensionMethodReturnsCorrectValue() - { - long oneWatt = 1; - Power power = oneWatt.Watts(); - Assert.Equal(1.0, power.Watts); - } - - [Fact] - public static void CreatingQuantityWithLongBackingFieldFromNullableLongWithExtensionMethodReturnsCorrectValue() - { - long? oneWatt = 1; - Power? power = oneWatt.Watts(); - Assert.NotNull(power); - Assert.Equal(1.0, power.Value.Watts); - } - - [Fact] - public static void CreatingQuantityWithLongBackingFieldFromNullableLongWithExtensionMethodReturnsNullWhenGivenNull() - { - long? nullLong = null; - Power? power = nullLong.Watts(); - Assert.Null(power); - } } } diff --git a/UnitsNet.Tests/NullableConstructors.cs b/UnitsNet.Tests/NullableConstructors.cs deleted file mode 100644 index 1322b96956..0000000000 --- a/UnitsNet.Tests/NullableConstructors.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using Xunit; -using UnitsNet.Units; - -namespace UnitsNet.Tests -{ - public class NullableConstructors - { - [Fact] - public void StaticConstructorWithNullReturnsNullWhenBackingTypeIsDouble() - { - Length? meter = Length.FromMeters(null); - Assert.False(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullAndEnumReturnsNullWhenBackingTypeIsDouble() - { - Length? meter = Length.From(null, LengthUnit.Meter); - Assert.False(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullAndEnumArgumentReturnsValueWhenInputArgumentHasValueWhenBackingTypeIsDouble() - { - double? value = 1.0; - Length? meter = Length.From(value, LengthUnit.Meter); - Assert.True(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullArgumentReturnsValueWhenInputArgumentHasValueWhenBackingTypeIsDouble() - { - double? value = 1.0; - Length? meter = Length.FromMeters(value); - Assert.True(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullReturnsNullWhenBackingTypeIsDecimal() - { - Information? meter = Information.FromBytes(null); - Assert.False(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullAndEnumReturnsNullWhenBackingTypeIsDecimal() - { - Information? meter = Information.From(null, InformationUnit.Byte); - Assert.False(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullAndEnumArgumentReturnsValueWhenInputArgumentHasValueWhenBackingTypeIsDecimal() - { - double? value = 1.0; - Information? meter = Information.From(value, InformationUnit.Byte); - Assert.True(meter.HasValue); - } - - [Fact] - public void StaticConstructorWithNullArgumentReturnsValueWhenInputArgumentHasValueWhenBackingTypeIsDecimal() - { - double? value = 1.0; - Information? meter = Information.FromBytes(value); - Assert.True(meter.HasValue); - } - } -} \ No newline at end of file diff --git a/UnitsNet.Tests/NumberExtensionsTest.cs b/UnitsNet.Tests/NumberExtensionsTest.cs deleted file mode 100644 index b79ab02e44..0000000000 --- a/UnitsNet.Tests/NumberExtensionsTest.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Xunit; -using UnitsNet.Extensions.NumberToAngle; -using UnitsNet.Extensions.NumberToForce; -using UnitsNet.Extensions.NumberToLength; -using UnitsNet.Extensions.NumberToMass; - -namespace UnitsNet.Tests -{ - public class NumberExtensionsTest - { - [Fact] - public void SomeArbitraryExtensionMethods_CreatesCorrectValue() - { - Assert.Equal(Length.FromMeters(1), 1.Meters()); - Assert.Equal(Mass.FromTonnes(2), 2.Tonnes()); - Assert.Equal(Force.FromKiloPonds(3), 3.KiloPonds()); - Assert.Equal(Angle.FromRadians(3), 3.Radians()); - } - } -} diff --git a/UnitsNet.Tests/QuantityTests.Ctor.cs b/UnitsNet.Tests/QuantityTests.Ctor.cs index ff13b7293d..29892d21e4 100644 --- a/UnitsNet.Tests/QuantityTests.Ctor.cs +++ b/UnitsNet.Tests/QuantityTests.Ctor.cs @@ -66,28 +66,22 @@ public void CtorWithOnlyValueOfRepresentativeTypes_SetsValueToGivenValueAndUnitT { #pragma warning disable 618 // double types - Assert.Equal(5, new Mass(5L).Value); - Assert.Equal(5, new Mass(5d).Value); - Assert.Equal(5, new Mass(5m).Value); - Assert.Equal(MassUnit.Kilogram, new Mass(5L).Unit); - Assert.Equal(MassUnit.Kilogram, new Mass(5d).Unit); - Assert.Equal(MassUnit.Kilogram, new Mass(5m).Unit); + Assert.Equal(5, new Mass(5L, MassUnit.Kilogram).Value); + Assert.Equal(5, new Mass(5d, MassUnit.Kilogram).Value); + Assert.Equal(MassUnit.Kilogram, new Mass(5L, MassUnit.Kilogram).Unit); + Assert.Equal(MassUnit.Kilogram, new Mass(5d, MassUnit.Kilogram).Unit); // decimal types - Assert.Equal(5, new Information(5L).Value); - Assert.Equal(5, new Information(5d).Value); - Assert.Equal(5, new Information(5m).Value); - Assert.Equal(InformationUnit.Bit, new Information(5L).Unit); - Assert.Equal(InformationUnit.Bit, new Information(5d).Unit); - Assert.Equal(InformationUnit.Bit, new Information(5m).Unit); + Assert.Equal(5, new Information(5L, InformationUnit.Bit).Value); + Assert.Equal(5, new Information(5m, InformationUnit.Bit).Value); + Assert.Equal(InformationUnit.Bit, new Information(5L, InformationUnit.Bit).Unit); + Assert.Equal(InformationUnit.Bit, new Information(5m, InformationUnit.Bit).Unit); // logarithmic types - Assert.Equal(5, new Level(5L).Value); - Assert.Equal(5, new Level(5d).Value); - Assert.Equal(5, new Level(5m).Value); - Assert.Equal(LevelUnit.Decibel, new Level(5L).Unit); - Assert.Equal(LevelUnit.Decibel, new Level(5d).Unit); - Assert.Equal(LevelUnit.Decibel, new Level(5m).Unit); + Assert.Equal(5, new Level(5L, LevelUnit.Decibel).Value); + Assert.Equal(5, new Level(5d, LevelUnit.Decibel).Value); + Assert.Equal(LevelUnit.Decibel, new Level(5L, LevelUnit.Decibel).Unit); + Assert.Equal(LevelUnit.Decibel, new Level(5d, LevelUnit.Decibel).Unit); #pragma warning restore 618 } diff --git a/UnitsNet.Tests/QuantityTests.ToString.cs b/UnitsNet.Tests/QuantityTests.ToString.cs index bab0e87a31..0c6c21e935 100644 --- a/UnitsNet.Tests/QuantityTests.ToString.cs +++ b/UnitsNet.Tests/QuantityTests.ToString.cs @@ -25,7 +25,7 @@ namespace UnitsNet.Tests { - [Collection(nameof(UnitSystemFixture))] + [Collection(nameof(UnitAbbreviationsCacheFixture))] public partial class QuantityTests { public class ToStringTests @@ -48,19 +48,16 @@ public void CreatedByCtorWithValue_ReturnsValueInBaseUnit() { #pragma warning disable 618 // double types - Assert.Equal("5 kg", new Mass(5L).ToString()); - Assert.Equal("5 kg", new Mass(5d).ToString()); - Assert.Equal("5 kg", new Mass(5m).ToString()); + Assert.Equal("5 kg", new Mass(5L, MassUnit.Kilogram).ToString()); + Assert.Equal("5 kg", new Mass(5d, MassUnit.Kilogram).ToString()); // decimal types - Assert.Equal("5 b", new Information(5L).ToString()); - Assert.Equal("5 b", new Information(5d).ToString()); - Assert.Equal("5 b", new Information(5m).ToString()); + Assert.Equal("5 b", new Information(5L, InformationUnit.Bit).ToString()); + Assert.Equal("5 b", new Information(5m, InformationUnit.Bit).ToString()); // logarithmic types - Assert.Equal("5 dB", new Level(5L).ToString()); - Assert.Equal("5 dB", new Level(5d).ToString()); - Assert.Equal("5 dB", new Level(5m).ToString()); + Assert.Equal("5 dB", new Level(5L, LevelUnit.Decibel).ToString()); + Assert.Equal("5 dB", new Level(5d, LevelUnit.Decibel).ToString()); #pragma warning restore 618 } @@ -82,10 +79,10 @@ public void CreatedByCtorWithValueAndUnit_ReturnsValueAndUnit() [Fact] public void ReturnsTheOriginalValueAndUnit() { - var oldCulture = UnitSystem.DefaultCulture; + var oldCulture = GlobalConfiguration.DefaultCulture; try { - UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; + GlobalConfiguration.DefaultCulture = CultureInfo.InvariantCulture; Assert.Equal("5 kg", Mass.FromKilograms(5).ToString()); Assert.Equal("5,000 g", Mass.FromGrams(5000).ToString()); Assert.Equal("1e-04 long tn", Mass.FromLongTons(1e-4).ToString()); @@ -98,59 +95,59 @@ public void ReturnsTheOriginalValueAndUnit() } finally { - UnitSystem.DefaultCulture = oldCulture; + GlobalConfiguration.DefaultCulture = oldCulture; } } [Fact] public void ConvertsToTheGivenUnit() { - var oldCulture = UnitSystem.DefaultCulture; + var oldCulture = GlobalConfiguration.DefaultCulture; try { - UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; - Assert.Equal("5,000 g", Mass.FromKilograms(5).ToString(MassUnit.Gram)); - Assert.Equal("5 kg", Mass.FromGrams(5000).ToString(MassUnit.Kilogram)); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter)); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch)); + GlobalConfiguration.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("5,000 g", Mass.FromKilograms(5).ToUnit(MassUnit.Gram).ToString()); + Assert.Equal("5 kg", Mass.FromGrams(5000).ToUnit(MassUnit.Kilogram).ToString()); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString()); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString()); } finally { - UnitSystem.DefaultCulture = oldCulture; + GlobalConfiguration.DefaultCulture = oldCulture; } } [Fact] public void FormatsNumberUsingGivenCulture() { - var oldCulture = UnitSystem.DefaultCulture; + var oldCulture = GlobalConfiguration.DefaultCulture; try { - UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, null)); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, CultureInfo.InvariantCulture)); - Assert.Equal("0,05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, new CultureInfo("nb-NO"))); + GlobalConfiguration.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(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 { - UnitSystem.DefaultCulture = oldCulture; + GlobalConfiguration.DefaultCulture = oldCulture; } } [Fact] public void FormatsNumberUsingGivenDigitsAfterRadix() { - var oldCulture = UnitSystem.DefaultCulture; + var oldCulture = GlobalConfiguration.DefaultCulture; try { - UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, null, 4)); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch, null, 2)); - Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch, null, 4)); + GlobalConfiguration.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(null, 4)); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString(null, 2)); + Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString(null, 4)); } finally { - UnitSystem.DefaultCulture = oldCulture; + GlobalConfiguration.DefaultCulture = oldCulture; } } } diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs new file mode 100644 index 0000000000..ce7a36b980 --- /dev/null +++ b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs @@ -0,0 +1,16 @@ +using Xunit; + +namespace UnitsNet.Tests +{ + [CollectionDefinition(nameof(UnitAbbreviationsCacheFixture), DisableParallelization = true)] + public class UnitAbbreviationsCacheFixture : ICollectionFixture + { + // This class has no code, and is never created. Its purpose is simply + // to be the place to apply [CollectionDefinition] and all the + // ICollectionFixture<> interfaces. + + // Apply this collection fixture to classes: + // 1. That rely on manipulating CultureInfo. See https://github.com/angularsen/UnitsNet/issues/436 + // 2. To avoid accessing static ToString/Parse from multiple tests where UnitAbbreviationsCache.Default is modified + } +} diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs new file mode 100644 index 0000000000..cfdf98338f --- /dev/null +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -0,0 +1,319 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using UnitsNet.Units; +using Xunit; +using Xunit.Abstractions; + +namespace UnitsNet.Tests +{ + [Collection(nameof(UnitAbbreviationsCacheFixture))] + public class UnitAbbreviationsCacheTests + { + private readonly ITestOutputHelper _output; + private const string AmericanCultureName = "en-US"; + private const string RussianCultureName = "ru-RU"; + private const string NorwegianCultureName = "nb-NO"; + + private static readonly IFormatProvider AmericanCulture = new CultureInfo(AmericanCultureName); + private static readonly IFormatProvider NorwegianCulture = new CultureInfo(NorwegianCultureName); + private static readonly IFormatProvider RussianCulture = new CultureInfo(RussianCultureName); + + public UnitAbbreviationsCacheTests(ITestOutputHelper output) + { + _output = output; + } + + // The default, parameterless ToString() method uses 2 sigifnificant digits after the radix point. + [Theory] + [InlineData(0, "0 m")] + [InlineData(0.1, "0.1 m")] + [InlineData(0.11, "0.11 m")] + [InlineData(0.111234, "0.11 m")] + [InlineData(0.115, "0.12 m")] + public void DefaultToStringFormatting(double value, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + Assert.Equal(expected, actual); + } + + private enum CustomUnit + { + // ReSharper disable UnusedMember.Local + Undefined = 0, + Unit1, + Unit2 + // ReSharper restore UnusedMember.Local + } + + // These cultures all use a comma for the radix point + [Theory] + [InlineData("de-DE")] + [InlineData("da-DK")] + [InlineData("es-AR")] + [InlineData("es-ES")] + [InlineData("it-IT")] + public void CommaRadixPointCultureFormatting(string culture) + { + Assert.Equal("0,12 m", Length.FromMeters(0.12).ToUnit(LengthUnit.Meter).ToString(GetCulture(culture))); + } + + // These cultures all use a decimal point for the radix point + [Theory] + [InlineData("en-CA")] + [InlineData("en-US")] + [InlineData("ar-EG")] + [InlineData("en-GB")] + [InlineData("es-MX")] + public void DecimalRadixPointCultureFormatting(string culture) + { + Assert.Equal("0.12 m", Length.FromMeters(0.12).ToUnit(LengthUnit.Meter).ToString(GetCulture(culture))); + } + + // These cultures all use a comma in digit grouping + [Theory] + [InlineData("en-CA")] + [InlineData("en-US")] + [InlineData("ar-EG")] + [InlineData("en-GB")] + [InlineData("es-MX")] + public void CommaDigitGroupingCultureFormatting(string cultureName) + { + CultureInfo culture = GetCulture(cultureName); + Assert.Equal("1,111 m", Length.FromMeters(1111).ToUnit(LengthUnit.Meter).ToString(culture)); + + // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. + // FeetInches returns a whole number of feet, with the remainder expressed (rounded) in inches. Same for SonePounds. + Assert.Equal("2,222 ft 3 in", + Length.FromFeetInches(2222, 3).FeetInches.ToString(culture)); + Assert.Equal("3,333 st 7 lb", + Mass.FromStonePounds(3333, 7).StonePounds.ToString(culture)); + } + + // These cultures use a thin space in digit grouping + [Theory] + [InlineData("nn-NO")] + [InlineData("fr-FR")] + public void SpaceDigitGroupingCultureFormatting(string culture) + { + // Note: the space used in digit groupings is actually a "thin space" Unicode character U+2009 + Assert.Equal("1 111 m", Length.FromMeters(1111).ToUnit(LengthUnit.Meter).ToString(GetCulture(culture))); + } + + // These cultures all use a decimal point in digit grouping + [Theory] + [InlineData("de-DE")] + [InlineData("da-DK")] + [InlineData("es-AR")] + [InlineData("es-ES")] + [InlineData("it-IT")] + public void DecimalPointDigitGroupingCultureFormatting(string culture) + { + Assert.Equal("1.111 m", Length.FromMeters(1111).ToUnit(LengthUnit.Meter).ToString(GetCulture(culture))); + } + + [Theory] + [InlineData(1, "1.1 m")] + [InlineData(2, "1.12 m")] + [InlineData(3, "1.123 m")] + [InlineData(4, "1.1235 m")] + [InlineData(5, "1.12346 m")] + [InlineData(6, "1.123457 m")] + public void CustomNumberOfSignificantDigitsAfterRadixFormatting(int significantDigitsAfterRadix, string expected) + { + string actual = Length.FromMeters(1.123456789).ToUnit(LengthUnit.Meter).ToString(AmericanCulture, significantDigitsAfterRadix); + Assert.Equal(expected, actual); + } + + // Due to rounding, the values will result in the same string representation regardless of the number of significant digits (up to a certain point) + [Theory] + [InlineData(0.819999999999, 2, "0.82 m")] + [InlineData(0.819999999999, 4, "0.82 m")] + [InlineData(0.00299999999, 2, "0.003 m")] + [InlineData(0.00299999999, 4, "0.003 m")] + [InlineData(0.0003000001, 2, "3e-04 m")] + [InlineData(0.0003000001, 4, "3e-04 m")] + public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value, + int maxSignificantDigitsAfterRadix, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture, maxSignificantDigitsAfterRadix); + Assert.Equal(expected, actual); + } + + // Any value in the interval (-inf ≤ x < 1e-03] is formatted in scientific notation + [Theory] + [InlineData(double.MinValue, "-1.8e+308 m")] + [InlineData(1.23e-120, "1.23e-120 m")] + [InlineData(0.0000111, "1.11e-05 m")] + [InlineData(1.99e-4, "1.99e-04 m")] + public void ScientificNotationLowerInterval(double value, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + Assert.Equal(expected, actual); + } + + // Any value in the interval [1e-03 ≤ x < 1e+03] is formatted in fixed point notation. + [Theory] + [InlineData(1e-3, "0.001 m")] + [InlineData(1.1, "1.1 m")] + [InlineData(999.99, "999.99 m")] + public void FixedPointNotationIntervalFormatting(double value, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + Assert.Equal(expected, actual); + } + + // Any value in the interval [1e+03 ≤ x < 1e+06] is formatted in fixed point notation with digit grouping. + [Theory] + [InlineData(1000, "1,000 m")] + [InlineData(11000, "11,000 m")] + [InlineData(111000, "111,000 m")] + [InlineData(999999.99, "999,999.99 m")] + public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + Assert.Equal(expected, actual); + } + + // Any value in the interval [1e+06 ≤ x ≤ +inf) is formatted in scientific notation. + [Theory] + [InlineData(1e6, "1e+06 m")] + [InlineData(11100000, "1.11e+07 m")] + [InlineData(double.MaxValue, "1.8e+308 m")] + public void ScientificNotationUpperIntervalFormatting(double value, string expected) + { + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + Assert.Equal(expected, actual); + } + + [Fact] + public void AllUnitsImplementToStringForInvariantCulture() + { + Assert.Equal("1 °", Angle.FromDegrees(1).ToString()); + Assert.Equal("1 m²", Area.FromSquareMeters(1).ToString()); + Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToString()); + Assert.Equal("1 N", Force.FromNewtons(1).ToString()); + Assert.Equal("1 m", Length.FromMeters(1).ToString()); + Assert.Equal("1 kg", Mass.FromKilograms(1).ToString()); + Assert.Equal("1 Pa", Pressure.FromPascals(1).ToString()); + Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToString()); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToString()); + Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToString()); + Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToString()); + Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToString()); + + Assert.Equal("2 ft 3 in", Length.FromFeetInches(2, 3).FeetInches.ToString()); + Assert.Equal("3 st 7 lb", Mass.FromStonePounds(3, 7).StonePounds.ToString()); + } + + [Fact] + public void ToString_WithNorwegianCulture() + { + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(NorwegianCulture)); + Assert.Equal("1 m²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(NorwegianCulture)); + Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(NorwegianCulture)); + Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 N", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(NorwegianCulture)); + Assert.Equal("1 m", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(NorwegianCulture)); + Assert.Equal("1 kg", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(NorwegianCulture)); + Assert.Equal("1 Pa", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(NorwegianCulture)); + Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(NorwegianCulture)); + Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(NorwegianCulture)); + Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(NorwegianCulture)); + } + + [Fact] + public void ToString_WithRussianCulture() + { + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(RussianCulture)); + Assert.Equal("1 м²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(RussianCulture)); + Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(RussianCulture)); + Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(RussianCulture)); + Assert.Equal("1 Н", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(RussianCulture)); + Assert.Equal("1 м", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(RussianCulture)); + Assert.Equal("1 кг", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(RussianCulture)); + Assert.Equal("1 Па", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(RussianCulture)); + Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(RussianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(RussianCulture)); + Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); + Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); + } + + [Fact] + public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() + { + var unitAbbreviationCache = new UnitAbbreviationsCache(); + Assert.Throws(() => unitAbbreviationCache.GetDefaultAbbreviation(CustomUnit.Unit1)); + } + + [Fact] + 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. + // Zulu (South Africa) + var zuluCulture = new CultureInfo("zu-ZA"); + CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = zuluCulture; + + var abbreviationsCache = new UnitAbbreviationsCache(); + abbreviationsCache.MapUnitToAbbreviation(CustomUnit.Unit1, AmericanCulture, "US english abbreviation for Unit1"); + + // Act + string abbreviation = abbreviationsCache.GetDefaultAbbreviation(CustomUnit.Unit1, zuluCulture); + + // Assert + Assert.Equal("US english abbreviation for Unit1", abbreviation); + } + finally + { + CultureInfo.CurrentCulture = oldCurrentCulture; + CultureInfo.CurrentUICulture = oldCurrentUICulture; + } + } + + [Fact] + public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviationForAlreadyMappedUnits() + { + var cache = new UnitAbbreviationsCache(); + cache.MapUnitToAbbreviation(AreaUnit.SquareMeter, AmericanCulture, "m^2"); + + Assert.Equal("m²", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter)); + } + + /// + /// Convenience method to the proper culture parameter type. + /// + private static CultureInfo GetCulture(string cultureName) + { + return new CultureInfo(cultureName); + } + } +} diff --git a/UnitsNet.Tests/UnitParserTests.cs b/UnitsNet.Tests/UnitParserTests.cs new file mode 100644 index 0000000000..a6d1dafd8f --- /dev/null +++ b/UnitsNet.Tests/UnitParserTests.cs @@ -0,0 +1,122 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests +{ + [Collection( nameof( UnitAbbreviationsCacheFixture ) )] + public class UnitParserTests + { + [Theory] + [InlineData("m^^2", AreaUnit.SquareMeter)] + [InlineData("cm^^2", AreaUnit.SquareCentimeter)] + public void Parse_ReturnsUnitMappedByCustomAbbreviation(string customAbbreviation, AreaUnit expected) + { + var abbrevCache = new UnitAbbreviationsCache(); + abbrevCache.MapUnitToAbbreviation(expected, customAbbreviation); + var parser = new UnitParser(abbrevCache); + + var actual = parser.Parse(customAbbreviation); + + Assert.Equal(expected, actual); + } + + [Fact] + public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() + { + Assert.Throws(() => UnitParser.Default.Parse("nonexistingunit")); + } + + [Fact] + public void ParseUnit_ShouldUseCorrectMicroSign() + { + // "\u00b5" = Micro sign + Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, Acceleration.ParseUnit("\u00b5m/s²")); + Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatio.ParseUnit("dB\u00b5V")); + Assert.Equal(AngleUnit.Microdegree, Angle.ParseUnit("\u00b5°")); + Assert.Equal(AngleUnit.Microradian, Angle.ParseUnit("\u00b5rad")); + Assert.Equal(AreaUnit.SquareMicrometer, Area.ParseUnit("\u00b5m²")); + Assert.Equal(DurationUnit.Microsecond, Duration.ParseUnit("\u00b5s")); + Assert.Equal(ElectricCurrentUnit.Microampere, ElectricCurrent.ParseUnit("\u00b5A")); + Assert.Equal(ElectricPotentialUnit.Microvolt, ElectricPotential.ParseUnit("\u00b5V")); + Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRate.ParseUnit("\u00b5N/s")); + Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLength.ParseUnit("\u00b5N/m")); + Assert.Equal(KinematicViscosityUnit.Microstokes, KinematicViscosity.ParseUnit("\u00b5St")); + Assert.Equal(LengthUnit.Microinch, Length.ParseUnit("\u00b5in")); + Assert.Equal(LengthUnit.Micrometer, Length.ParseUnit("\u00b5m")); + Assert.Equal(MassFlowUnit.MicrogramPerSecond, MassFlow.ParseUnit("\u00b5g/S")); + Assert.Equal(MassUnit.Microgram, Mass.ParseUnit("\u00b5g")); + Assert.Equal(PowerUnit.Microwatt, Power.ParseUnit("\u00b5W")); + Assert.Equal(PressureUnit.Micropascal, Pressure.ParseUnit("\u00b5Pa")); + Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeed.ParseUnit("\u00b5°/s")); + Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeed.ParseUnit("\u00b5rad/s")); + Assert.Equal(SpeedUnit.MicrometerPerMinute, Speed.ParseUnit("\u00b5m/min")); + Assert.Equal(SpeedUnit.MicrometerPerSecond, Speed.ParseUnit("\u00b5m/s")); + Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRate.ParseUnit("\u00b5°C/s")); + Assert.Equal(VolumeUnit.Microliter, Volume.ParseUnit("\u00b5l")); + Assert.Equal(VolumeUnit.CubicMicrometer, Volume.ParseUnit("\u00b5m³")); + Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, VolumeFlow.ParseUnit("\u00b5LPM")); + + // "\u03bc" = Lower case greek letter 'Mu' + Assert.Throws(() => Acceleration.ParseUnit("\u03bcm/s²")); + Assert.Throws(() => AmplitudeRatio.ParseUnit("dB\u03bcV")); + Assert.Throws(() => Angle.ParseUnit("\u03bc°")); + Assert.Throws(() => Angle.ParseUnit("\u03bcrad")); + Assert.Throws(() => Area.ParseUnit("\u03bcm²")); + Assert.Throws(() => Duration.ParseUnit("\u03bcs")); + Assert.Throws(() => ElectricCurrent.ParseUnit("\u03bcA")); + Assert.Throws(() => ElectricPotential.ParseUnit("\u03bcV")); + Assert.Throws(() => ForceChangeRate.ParseUnit("\u03bcN/s")); + Assert.Throws(() => ForcePerLength.ParseUnit("\u03bcN/m")); + Assert.Throws(() => KinematicViscosity.ParseUnit("\u03bcSt")); + Assert.Throws(() => Length.ParseUnit("\u03bcin")); + Assert.Throws(() => Length.ParseUnit("\u03bcm")); + Assert.Throws(() => MassFlow.ParseUnit("\u03bcg/S")); + Assert.Throws(() => Mass.ParseUnit("\u03bcg")); + Assert.Throws(() => Power.ParseUnit("\u03bcW")); + Assert.Throws(() => Pressure.ParseUnit("\u03bcPa")); + Assert.Throws(() => RotationalSpeed.ParseUnit("\u03bc°/s")); + Assert.Throws(() => RotationalSpeed.ParseUnit("\u03bcrad/s")); + Assert.Throws(() => Speed.ParseUnit("\u03bcm/min")); + Assert.Throws(() => Speed.ParseUnit("\u03bcm/s")); + Assert.Throws(() => TemperatureChangeRate.ParseUnit("\u03bc°C/s")); + Assert.Throws(() => Volume.ParseUnit("\u03bcl")); + Assert.Throws(() => Volume.ParseUnit("\u03bcm³")); + Assert.Throws(() => VolumeFlow.ParseUnit("\u03bcLPM")); + } + + [Fact] + public void Parse_AmbiguousUnitsThrowsException() + { + // Act 1 + var exception1 = Assert.Throws(() => UnitParser.Default.Parse("pt")); + + // Act 2 + var exception2 = Assert.Throws(() => Length.Parse("1 pt")); + + // Assert + Assert.Equal("Cannot parse \"pt\" since it could be either of these: DtpPoint, PrinterPoint", exception1.Message); + Assert.Equal("Cannot parse \"pt\" since it could be either of these: DtpPoint, PrinterPoint", exception2.Message); + } + } +} diff --git a/UnitsNet.Tests/UnitSystemFixture.cs b/UnitsNet.Tests/UnitSystemFixture.cs deleted file mode 100644 index a396cb0b2f..0000000000 --- a/UnitsNet.Tests/UnitSystemFixture.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Xunit; - -namespace UnitsNet.Tests -{ - [CollectionDefinition(nameof(UnitSystemFixture), DisableParallelization = true)] - public class UnitSystemFixture : ICollectionFixture - { - // This class has no code, and is never created. Its purpose is simply - // to be the place to apply [CollectionDefinition] and all the - // ICollectionFixture<> interfaces. - - // Apply this collection fixture to classes: - // 1. that rely on manipulating CultureInfo. See https://github.com/angularsen/UnitsNet/issues/436 - // 2. to avoid accessing static prop DefaultToString in parallel from multiple tests: - // a. UnitSystemTests.DefaultToStringFormatting() - // b. LengthTests.ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() - } -} diff --git a/UnitsNet.Tests/UnitSystemTests.cs b/UnitsNet.Tests/UnitSystemTests.cs index 1bdb3f34c2..2a52e693c5 100644 --- a/UnitsNet.Tests/UnitSystemTests.cs +++ b/UnitsNet.Tests/UnitSystemTests.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,480 +20,152 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; -using System.Linq; -using Xunit; using UnitsNet.Units; -using Xunit.Abstractions; -using System.Globalization; +using Xunit; namespace UnitsNet.Tests { - [Collection(nameof(UnitSystemFixture))] public class UnitSystemTests { - private readonly ITestOutputHelper _output; - private const string AmericanCultureName = "en-US"; - private const string RussianCultureName = "ru-RU"; - private const string NorwegianCultureName = "nb-NO"; - - private static readonly IFormatProvider AmericanCulture = new CultureInfo(AmericanCultureName); - private static readonly IFormatProvider NorwegianCulture = new CultureInfo(NorwegianCultureName); - private static readonly IFormatProvider RussianCulture = new CultureInfo(RussianCultureName); - - public UnitSystemTests(ITestOutputHelper output) + [Fact] + public void ConstructorImplementedProperly() { - _output = output; - } + var baseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - // The default, parameterless ToString() method uses 2 sigifnificant digits after the radix point. - [Theory] - [InlineData(0, "0 m")] - [InlineData(0.1, "0.1 m")] - [InlineData(0.11, "0.11 m")] - [InlineData(0.111234, "0.11 m")] - [InlineData(0.115, "0.12 m")] - public void DefaultToStringFormatting(double value, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture); - Assert.Equal(expected, actual); - } + var unitSystem = new UnitSystem(baseUnits); - private enum CustomUnit - { - // ReSharper disable UnusedMember.Local - Undefined = 0, - Unit1, - Unit2 - // ReSharper restore UnusedMember.Local + Assert.Equal(unitSystem.BaseUnits, baseUnits); } - private static IEnumerable GetUnitTypesWithMissingAbbreviations(string cultureName, - IEnumerable unitValues) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable + [Fact] + public void ConstructorThrowsArgumentNullExceptionForNullBaseUnits() { - UnitSystem unitSystem = UnitSystem.GetCached(GetCulture(cultureName)); - - var unitsMissingAbbreviations = new List(); - foreach (TUnitType unit in unitValues) - { - try - { - unitSystem.GetDefaultAbbreviation(unit); - } - catch - { - unitsMissingAbbreviations.Add(unit); - } - } - - return unitsMissingAbbreviations.Cast(); + Assert.Throws(() => new UnitSystem(null)); } - // These cultures all use a comma for the radix point [Theory] - [InlineData("de-DE")] - [InlineData("da-DK")] - [InlineData("es-AR")] - [InlineData("es-ES")] - [InlineData("it-IT")] - public void CommaRadixPointCultureFormatting(string culture) + [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) { - Assert.Equal("0,12 m", Length.FromMeters(0.12).ToString(LengthUnit.Meter, GetCulture(culture))); + var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); + Assert.Throws(() => new UnitSystem(baseUnits)); } - // These cultures all use a decimal point for the radix point - [Theory] - [InlineData("en-CA")] - [InlineData("en-US")] - [InlineData("ar-EG")] - [InlineData("en-GB")] - [InlineData("es-MX")] - public void DecimalRadixPointCultureFormatting(string culture) + [Fact] + public void EqualsObjectIsImplementedCorrectly() { - Assert.Equal("0.12 m", Length.FromMeters(0.12).ToString(LengthUnit.Meter, GetCulture(culture))); - } + var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // These cultures all use a comma in digit grouping - [Theory] - [InlineData("en-CA")] - [InlineData("en-US")] - [InlineData("ar-EG")] - [InlineData("en-GB")] - [InlineData("es-MX")] - public void CommaDigitGroupingCultureFormatting(string cultureName) - { - CultureInfo culture = GetCulture(cultureName); - Assert.Equal("1,111 m", Length.FromMeters(1111).ToString(LengthUnit.Meter, culture)); - - // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. - // FeetInches returns a whole number of feet, with the remainder expressed (rounded) in inches. Same for SonePounds. - Assert.Equal("2,222 ft 3 in", - Length.FromFeetInches(2222, 3).FeetInches.ToString(culture)); - Assert.Equal("3,333 st 7 lb", - Mass.FromStonePounds(3333, 7).StonePounds.ToString(culture)); - } + var unitSystem2 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // These cultures use a thin space in digit grouping - [Theory] - [InlineData("nn-NO")] - [InlineData("fr-FR")] - public void SpaceDigitGroupingCultureFormatting(string culture) - { - // Note: the space used in digit groupings is actually a "thin space" Unicode character U+2009 - Assert.Equal("1 111 m", Length.FromMeters(1111).ToString(LengthUnit.Meter, GetCulture(culture))); - } + var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // These cultures all use a decimal point in digit grouping - [Theory] - [InlineData("de-DE")] - [InlineData("da-DK")] - [InlineData("es-AR")] - [InlineData("es-ES")] - [InlineData("it-IT")] - public void DecimalPointDigitGroupingCultureFormatting(string culture) - { - Assert.Equal("1.111 m", Length.FromMeters(1111).ToString(LengthUnit.Meter, GetCulture(culture))); - } + Assert.True(unitSystem1.Equals((object)unitSystem2)); + Assert.False(unitSystem1.Equals((object)unitSystem3)); - [Theory] - [InlineData("m^^2", AreaUnit.SquareMeter)] - [InlineData("cm^^2", AreaUnit.SquareCentimeter)] - public void Parse_ReturnsUnitMappedByCustomAbbreviation(string customAbbreviation, AreaUnit expected) - { - UnitSystem unitSystem = UnitSystem.Default; - unitSystem.MapUnitToAbbreviation(expected, customAbbreviation); - var actual = unitSystem.Parse(customAbbreviation); - Assert.Equal(expected, actual); + Assert.False(unitSystem1.Equals("Some object.")); + Assert.False(unitSystem1.Equals((IFormatProvider)null)); } [Fact] - public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() + public void EqualsUnitSystemIsImplementedCorrectly() { - Assert.Throws(() => UnitSystem.Default.Parse("nonexistingunit")); - } + var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Theory] - [InlineData(1, "1.1 m")] - [InlineData(2, "1.12 m")] - [InlineData(3, "1.123 m")] - [InlineData(4, "1.1235 m")] - [InlineData(5, "1.12346 m")] - [InlineData(6, "1.123457 m")] - public void CustomNumberOfSignificantDigitsAfterRadixFormatting(int significantDigitsAfterRadix, string expected) - { - string actual = Length.FromMeters(1.123456789).ToString(LengthUnit.Meter, AmericanCulture, significantDigitsAfterRadix); - Assert.Equal(expected, actual); - } + var unitSystem2 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // Due to rounding, the values will result in the same string representation regardless of the number of significant digits (up to a certain point) - [Theory] - [InlineData(0.819999999999, 2, "0.82 m")] - [InlineData(0.819999999999, 4, "0.82 m")] - [InlineData(0.00299999999, 2, "0.003 m")] - [InlineData(0.00299999999, 4, "0.003 m")] - [InlineData(0.0003000001, 2, "3e-04 m")] - [InlineData(0.0003000001, 4, "3e-04 m")] - public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value, - int maxSignificantDigitsAfterRadix, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture, maxSignificantDigitsAfterRadix); - Assert.Equal(expected, actual); - } + var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // Any value in the interval (-inf ≤ x < 1e-03] is formatted in scientific notation - [Theory] - [InlineData(double.MinValue, "-1.8e+308 m")] - [InlineData(1.23e-120, "1.23e-120 m")] - [InlineData(0.0000111, "1.11e-05 m")] - [InlineData(1.99e-4, "1.99e-04 m")] - public void ScientificNotationLowerInterval(double value, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture); - Assert.Equal(expected, actual); - } + Assert.True(unitSystem1.Equals(unitSystem2)); + Assert.True(unitSystem2.Equals(unitSystem1)); - // Any value in the interval [1e-03 ≤ x < 1e+03] is formatted in fixed point notation. - [Theory] - [InlineData(1e-3, "0.001 m")] - [InlineData(1.1, "1.1 m")] - [InlineData(999.99, "999.99 m")] - public void FixedPointNotationIntervalFormatting(double value, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture); - Assert.Equal(expected, actual); - } + Assert.False(unitSystem1.Equals(unitSystem3)); + Assert.False(unitSystem3.Equals(unitSystem1)); - // Any value in the interval [1e+03 ≤ x < 1e+06] is formatted in fixed point notation with digit grouping. - [Theory] - [InlineData(1000, "1,000 m")] - [InlineData(11000, "11,000 m")] - [InlineData(111000, "111,000 m")] - [InlineData(999999.99, "999,999.99 m")] - public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture); - Assert.Equal(expected, actual); - } - - // Any value in the interval [1e+06 ≤ x ≤ +inf) is formatted in scientific notation. - [Theory] - [InlineData(1e6, "1e+06 m")] - [InlineData(11100000, "1.11e+07 m")] - [InlineData(double.MaxValue, "1.8e+308 m")] - public void ScientificNotationUpperIntervalFormatting(double value, string expected) - { - string actual = Length.FromMeters(value).ToString(LengthUnit.Meter, AmericanCulture); - Assert.Equal(expected, actual); + Assert.False(unitSystem1.Equals(null)); } [Fact] - public void ShouldUseCorrectMicroSign() + public void EqualityOperatorIsImplementedCorrectly() { - // "\u00b5" = Micro sign - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, Acceleration.ParseUnit("\u00b5m/s²")); - Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatio.ParseUnit("dB\u00b5V")); - Assert.Equal(AngleUnit.Microdegree, Angle.ParseUnit("\u00b5°")); - Assert.Equal(AngleUnit.Microradian, Angle.ParseUnit("\u00b5rad")); - Assert.Equal(AreaUnit.SquareMicrometer, Area.ParseUnit("\u00b5m²")); - Assert.Equal(DurationUnit.Microsecond, Duration.ParseUnit("\u00b5s")); - Assert.Equal(ElectricCurrentUnit.Microampere, ElectricCurrent.ParseUnit("\u00b5A")); - Assert.Equal(ElectricPotentialUnit.Microvolt, ElectricPotential.ParseUnit("\u00b5V")); - Assert.Equal(FlowUnit.MicrolitersPerMinute, Flow.ParseUnit("\u00b5LPM")); - Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRate.ParseUnit("\u00b5N/s")); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLength.ParseUnit("\u00b5N/m")); - Assert.Equal(KinematicViscosityUnit.Microstokes, KinematicViscosity.ParseUnit("\u00b5St")); - Assert.Equal(LengthUnit.Microinch, Length.ParseUnit("\u00b5in")); - Assert.Equal(LengthUnit.Micrometer, Length.ParseUnit("\u00b5m")); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, MassFlow.ParseUnit("\u00b5g/S")); - Assert.Equal(MassUnit.Microgram, Mass.ParseUnit("\u00b5g")); - Assert.Equal(PowerUnit.Microwatt, Power.ParseUnit("\u00b5W")); - Assert.Equal(PressureUnit.Micropascal, Pressure.ParseUnit("\u00b5Pa")); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeed.ParseUnit("\u00b5°/s")); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeed.ParseUnit("\u00b5rad/s")); - Assert.Equal(SpeedUnit.MicrometerPerMinute, Speed.ParseUnit("\u00b5m/min")); - Assert.Equal(SpeedUnit.MicrometerPerSecond, Speed.ParseUnit("\u00b5m/s")); - Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRate.ParseUnit("\u00b5°C/s")); - Assert.Equal(VolumeUnit.Microliter, Volume.ParseUnit("\u00b5l")); - Assert.Equal(VolumeUnit.CubicMicrometer, Volume.ParseUnit("\u00b5m³")); - - // "\u03bc" = Lower case greek letter 'Mu' - Assert.Throws(() => Acceleration.ParseUnit("\u03bcm/s²")); - Assert.Throws(() => AmplitudeRatio.ParseUnit("dB\u03bcV")); - Assert.Throws(() => Angle.ParseUnit("\u03bc°")); - Assert.Throws(() => Angle.ParseUnit("\u03bcrad")); - Assert.Throws(() => Area.ParseUnit("\u03bcm²")); - Assert.Throws(() => Duration.ParseUnit("\u03bcs")); - Assert.Throws(() => ElectricCurrent.ParseUnit("\u03bcA")); - Assert.Throws(() => ElectricPotential.ParseUnit("\u03bcV")); - Assert.Throws(() => Flow.ParseUnit("\u03bcLPM")); - Assert.Throws(() => ForceChangeRate.ParseUnit("\u03bcN/s")); - Assert.Throws(() => ForcePerLength.ParseUnit("\u03bcN/m")); - Assert.Throws(() => KinematicViscosity.ParseUnit("\u03bcSt")); - Assert.Throws(() => Length.ParseUnit("\u03bcin")); - Assert.Throws(() => Length.ParseUnit("\u03bcm")); - Assert.Throws(() => MassFlow.ParseUnit("\u03bcg/S")); - Assert.Throws(() => Mass.ParseUnit("\u03bcg")); - Assert.Throws(() => Power.ParseUnit("\u03bcW")); - Assert.Throws(() => Pressure.ParseUnit("\u03bcPa")); - Assert.Throws(() => RotationalSpeed.ParseUnit("\u03bc°/s")); - Assert.Throws(() => RotationalSpeed.ParseUnit("\u03bcrad/s")); - Assert.Throws(() => Speed.ParseUnit("\u03bcm/min")); - Assert.Throws(() => Speed.ParseUnit("\u03bcm/s")); - Assert.Throws(() => TemperatureChangeRate.ParseUnit("\u03bc°C/s")); - Assert.Throws(() => Volume.ParseUnit("\u03bcl")); - Assert.Throws(() => Volume.ParseUnit("\u03bcm³")); - } + var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Theory] - [InlineData("en-US")] - [InlineData("nb-NO")] - [InlineData("ru-RU")] - public void AllUnitAbbreviationsImplemented(string cultureName) - { - List unitValuesMissingAbbreviations = new List() - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, - EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .Concat(GetUnitTypesWithMissingAbbreviations(cultureName, EnumUtils.GetEnumValues())) - .ToList(); - - // We want to flag if any localizations are missing, but not break the build - // or flag an error for pull requests. For now they are not considered - // critical and it is cumbersome to have a third person review the pull request - // and add in any translations before merging it in. - if (unitValuesMissingAbbreviations.Any()) - { - string unitsWithNoAbbrev = string.Join(", ", - unitValuesMissingAbbreviations.Select(unitValue => unitValue.GetType().Name + "." + unitValue).ToArray()); - - string message = "Units missing abbreviations: " + unitsWithNoAbbrev; - _output.WriteLine(message); - } - Assert.Empty(unitValuesMissingAbbreviations); - } + var unitSystem2 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Fact] - public void AllUnitsImplementToStringForInvariantCulture() - { - Assert.Equal("1 °", Angle.FromDegrees(1).ToString()); - Assert.Equal("1 m²", Area.FromSquareMeters(1).ToString()); - Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToString()); - Assert.Equal("1 m³/s", Flow.FromCubicMetersPerSecond(1).ToString()); - Assert.Equal("1 N", Force.FromNewtons(1).ToString()); - Assert.Equal("1 m", Length.FromMeters(1).ToString()); - Assert.Equal("1 kg", Mass.FromKilograms(1).ToString()); - Assert.Equal("1 Pa", Pressure.FromPascals(1).ToString()); - Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToString()); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToString()); - Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToString()); - Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToString()); - - Assert.Equal("2 ft 3 in", Length.FromFeetInches(2, 3).FeetInches.ToString()); - Assert.Equal("3 st 7 lb", Mass.FromStonePounds(3, 7).StonePounds.ToString()); - } + var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Fact] - public void ToString_WithNorwegianCulture() - { - Assert.Equal("1 °", Angle.FromDegrees(1).ToString(AngleUnit.Degree, NorwegianCulture)); - Assert.Equal("1 m²", Area.FromSquareMeters(1).ToString(AreaUnit.SquareMeter, NorwegianCulture)); - Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToString(ElectricPotentialUnit.Volt, NorwegianCulture)); - Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToString(VolumeFlowUnit.CubicMeterPerSecond, NorwegianCulture)); - Assert.Equal("1 N", Force.FromNewtons(1).ToString(ForceUnit.Newton, NorwegianCulture)); - Assert.Equal("1 m", Length.FromMeters(1).ToString(LengthUnit.Meter, NorwegianCulture)); - Assert.Equal("1 kg", Mass.FromKilograms(1).ToString(MassUnit.Kilogram, NorwegianCulture)); - Assert.Equal("1 Pa", Pressure.FromPascals(1).ToString(PressureUnit.Pascal, NorwegianCulture)); - Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToString(RotationalSpeedUnit.RadianPerSecond, NorwegianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToString(TemperatureUnit.Kelvin, NorwegianCulture)); - Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToString(TorqueUnit.NewtonMeter, NorwegianCulture)); - Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToString(VolumeUnit.CubicMeter, NorwegianCulture)); - } + Assert.True(unitSystem1 == unitSystem2); + Assert.True(unitSystem2 == unitSystem1); - [Fact] - public void ToString_WithRussianCulture() - { - Assert.Equal("1 °", Angle.FromDegrees(1).ToString(AngleUnit.Degree, RussianCulture)); - Assert.Equal("1 м²", Area.FromSquareMeters(1).ToString(AreaUnit.SquareMeter, RussianCulture)); - Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToString(ElectricPotentialUnit.Volt, RussianCulture)); - Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToString(VolumeFlowUnit.CubicMeterPerSecond, RussianCulture)); - Assert.Equal("1 Н", Force.FromNewtons(1).ToString(ForceUnit.Newton, RussianCulture)); - Assert.Equal("1 м", Length.FromMeters(1).ToString(LengthUnit.Meter, RussianCulture)); - Assert.Equal("1 кг", Mass.FromKilograms(1).ToString(MassUnit.Kilogram, RussianCulture)); - Assert.Equal("1 Па", Pressure.FromPascals(1).ToString(PressureUnit.Pascal, RussianCulture)); - Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToString(RotationalSpeedUnit.RadianPerSecond, RussianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToString(TemperatureUnit.Kelvin, RussianCulture)); - Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToString(TorqueUnit.NewtonMeter, RussianCulture)); - Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToString(VolumeUnit.CubicMeter, RussianCulture)); - } + Assert.False(unitSystem1 == unitSystem3); + Assert.False(unitSystem3 == unitSystem1); - [Fact] - public void GetDefaultAbbreviationFallsBackToDefaultStringIfNotSpecified() - { - UnitSystem usUnits = new UnitSystem(AmericanCultureName); - string abbreviation = usUnits.GetDefaultAbbreviation(CustomUnit.Unit1); - Assert.Equal("(no abbreviation for CustomUnit.Unit1)", abbreviation); - } + Assert.False(unitSystem1 == null); + Assert.False(null == unitSystem1); - [Fact] - public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() - { - CultureInfo oldCurrentCulture = CultureInfo.CurrentCulture; - CultureInfo oldCurrentUICulture = CultureInfo.CurrentUICulture; - - try - { - // CurrentCulture affects number formatting, such as comma or dot as decimal separator. - // CurrentUICulture affects localization, in this case the abbreviation. - // Zulu (South Africa) - var zuluCulture = new CultureInfo("zu-ZA"); - UnitSystem zuluUnits = UnitSystem.GetCached(zuluCulture); - CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = zuluCulture; - - UnitSystem usUnits = UnitSystem.GetCached(AmericanCultureName); - usUnits.MapUnitToAbbreviation(CustomUnit.Unit1, "US english abbreviation for Unit1"); - - // Act - string abbreviation = zuluUnits.GetDefaultAbbreviation(CustomUnit.Unit1); - - // Assert - Assert.Equal("US english abbreviation for Unit1", abbreviation); - } - finally - { - CultureInfo.CurrentCulture = oldCurrentCulture; - CultureInfo.CurrentUICulture = oldCurrentUICulture; - } - } - - [Fact] - public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviationForAlreadyMappedUnits() - { - UnitSystem unitSystem = UnitSystem.GetCached(AmericanCultureName); - unitSystem.MapUnitToAbbreviation(AreaUnit.SquareMeter, "m^2"); + UnitSystem nullUnitSystem1 = null; + UnitSystem nullUnitSystem2 = null; - Assert.Equal("m²", unitSystem.GetDefaultAbbreviation(AreaUnit.SquareMeter)); + Assert.True(nullUnitSystem1 == nullUnitSystem2); } [Fact] - public void NegativeInfinityFormatting() + public void InequalityOperatorIsImplementedCorrectly() { - Assert.Equal("-Infinity m", Length.FromMeters(double.NegativeInfinity).ToString(LengthUnit.Meter, CultureInfo.InvariantCulture)); - } + var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Fact] - public void NotANumberFormatting() - { - Assert.Equal("NaN m", Length.FromMeters(double.NaN).ToString()); - } + var unitSystem2 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - [Fact] - public void Parse_AmbiguousUnitsThrowsException() - { - UnitSystem unitSystem = UnitSystem.Default; + var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - // Act 1 - var exception1 = Assert.Throws(() => unitSystem.Parse("tsp")); + Assert.False(unitSystem1 != unitSystem2); + Assert.False(unitSystem2 != unitSystem1); - // Act 2 - var exception2 = Assert.Throws(() => Volume.Parse("1 tsp")); + Assert.True(unitSystem1 != unitSystem3); + Assert.True(unitSystem3 != unitSystem1); - // Assert - Assert.Equal("Cannot parse \"tsp\" since it could be either of these: MetricTeaspoon, Teaspoon", exception1.Message); - Assert.Equal("Cannot parse \"tsp\" since it could be either of these: MetricTeaspoon, Teaspoon", exception2.Message); - } + Assert.True(unitSystem1 != null); + Assert.True(null != unitSystem1); - [Fact] - public void Parse_UnambiguousUnitsDoesNotThrow() - { - Volume unit = Volume.Parse("1 l"); + UnitSystem nullUnitSystem1 = null; + UnitSystem nullUnitSystem2 = null; - Assert.Equal(Volume.FromLiters(1), unit); + Assert.False(nullUnitSystem1 != nullUnitSystem2); } [Fact] - public void PositiveInfinityFormatting() - { - Assert.Equal("Infinity m", Length.FromMeters(double.PositiveInfinity).ToString(LengthUnit.Meter, CultureInfo.InvariantCulture)); - } - - /// - /// Convenience method to the proper culture parameter type. - /// - private static CultureInfo GetCulture(string cultureName) - { - return new CultureInfo(cultureName); + 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); + Assert.Equal(ElectricCurrentUnit.Ampere, UnitSystem.SI.BaseUnits.Current); + Assert.Equal(TemperatureUnit.Kelvin, UnitSystem.SI.BaseUnits.Temperature); + Assert.Equal(AmountOfSubstanceUnit.Mole, UnitSystem.SI.BaseUnits.Amount); + Assert.Equal(LuminousIntensityUnit.Candela, UnitSystem.SI.BaseUnits.LuminousIntensity); } } } diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 132a701a43..f85034390c 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -1,9 +1,10 @@  - netcoreapp1.1 + netcoreapp2.0 UnitsNet.Tests CS1701;CS1702;CS1705;CS0618 + 7.3 diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs index 1832f89807..683d1e5f9f 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Acceleration + public sealed partial class Acceleration : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly AccelerationUnit? _unit; + + static Acceleration() + { + BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit MeterPerSecondSquared. /// @@ -75,28 +80,334 @@ public Acceleration() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Acceleration(double numericValue, AccelerationUnit unit) + { + if(unit == AccelerationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. + /// + public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; + + /// + /// Represents the largest possible value of Acceleration + /// + public static Acceleration MaxValue => new Acceleration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Acceleration + /// + public static Acceleration MinValue => new Acceleration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Acceleration; + + /// + /// All units of measurement for the Acceleration quantity. + /// + public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// + public static Acceleration Zero => new Acceleration(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Acceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Acceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Acceleration in CentimetersPerSecondSquared. + /// + public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); + + /// + /// Get Acceleration in DecimetersPerSecondSquared. + /// + public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); + + /// + /// Get Acceleration in FeetPerSecondSquared. + /// + public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); + + /// + /// Get Acceleration in InchesPerSecondSquared. + /// + public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); + + /// + /// Get Acceleration in KilometersPerSecondSquared. + /// + public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); + + /// + /// Get Acceleration in KnotsPerHour. + /// + public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); + + /// + /// Get Acceleration in KnotsPerMinute. + /// + public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); + + /// + /// Get Acceleration in KnotsPerSecond. + /// + public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); + + /// + /// Get Acceleration in MetersPerSecondSquared. + /// + public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); + + /// + /// Get Acceleration in MicrometersPerSecondSquared. + /// + public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); + + /// + /// Get Acceleration in MillimetersPerSecondSquared. + /// + public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); + + /// + /// Get Acceleration in NanometersPerSecondSquared. + /// + public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); + + /// + /// Get Acceleration in StandardGravity. + /// + public double StandardGravity => As(AccelerationUnit.StandardGravity); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AccelerationUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Acceleration from CentimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromCentimetersPerSecondSquared(double centimeterspersecondsquared) + { + double value = (double) centimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); + } + /// + /// Get Acceleration from DecimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromDecimetersPerSecondSquared(double decimeterspersecondsquared) + { + double value = (double) decimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); + } + /// + /// Get Acceleration from FeetPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) + { + double value = (double) feetpersecondsquared; + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); + } + /// + /// Get Acceleration from InchesPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) + { + double value = (double) inchespersecondsquared; + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); + } + /// + /// Get Acceleration from KilometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKilometersPerSecondSquared(double kilometerspersecondsquared) + { + double value = (double) kilometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); + } + /// + /// Get Acceleration from KnotsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerHour(double knotsperhour) + { + double value = (double) knotsperhour; + return new Acceleration(value, AccelerationUnit.KnotPerHour); + } + /// + /// Get Acceleration from KnotsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerMinute(double knotsperminute) + { + double value = (double) knotsperminute; + return new Acceleration(value, AccelerationUnit.KnotPerMinute); + } + /// + /// Get Acceleration from KnotsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromKnotsPerSecond(double knotspersecond) + { + double value = (double) knotspersecond; + return new Acceleration(value, AccelerationUnit.KnotPerSecond); + } + /// + /// Get Acceleration from MetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMetersPerSecondSquared(double meterspersecondsquared) + { + double value = (double) meterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); + } + /// + /// Get Acceleration from MicrometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMicrometersPerSecondSquared(double micrometerspersecondsquared) + { + double value = (double) micrometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); + } + /// + /// Get Acceleration from MillimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromMillimetersPerSecondSquared(double millimeterspersecondsquared) + { + double value = (double) millimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); + } + /// + /// Get Acceleration from NanometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromNanometersPerSecondSquared(double nanometerspersecondsquared) + { + double value = (double) nanometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); + } + /// + /// Get Acceleration from StandardGravity. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Acceleration FromStandardGravity(double standardgravity) + { + double value = (double) standardgravity; + return new Acceleration(value, AccelerationUnit.StandardGravity); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +426,363 @@ public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Acceleration Parse(string str, [CanBeNull] string cultureName) + public static Acceleration Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AccelerationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersPerSecondSquared(x.MetersPerSecondSquared + y.MetersPerSecondSquared)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Acceleration); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AccelerationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to 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."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == AccelerationUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Acceleration. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AccelerationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Acceleration to another Acceleration with the unit representation . + /// + /// A Acceleration with the specified unit. + public Acceleration ToUnit(AccelerationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Acceleration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; + case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; + case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; + case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; + case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return _value; + case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; + case AccelerationUnit.StandardGravity: return _value*9.80665; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(AccelerationUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; + case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; + case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; + case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; + case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; + case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; + case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AccelerationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs index 47a945e754..289ef02cee 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AmountOfSubstance + public sealed partial class AmountOfSubstance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmountOfSubstanceUnit? _unit; + static AmountOfSubstance() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Mole. /// @@ -75,28 +80,364 @@ public AmountOfSubstance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private AmountOfSubstance(double numericValue, AmountOfSubstanceUnit unit) + { + if(unit == AmountOfSubstanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. + /// + public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; + + /// + /// Represents the largest possible value of AmountOfSubstance + /// + public static AmountOfSubstance MaxValue => new AmountOfSubstance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AmountOfSubstance + /// + public static AmountOfSubstance MinValue => new AmountOfSubstance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AmountOfSubstance; + + /// + /// All units of measurement for the AmountOfSubstance quantity. + /// + public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Mole. + /// + public static AmountOfSubstance Zero => new AmountOfSubstance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmountOfSubstance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AmountOfSubstance in Centimoles. + /// + public double Centimoles => As(AmountOfSubstanceUnit.Centimole); + + /// + /// Get AmountOfSubstance in CentipoundMoles. + /// + public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); + + /// + /// Get AmountOfSubstance in Decimoles. + /// + public double Decimoles => As(AmountOfSubstanceUnit.Decimole); + + /// + /// Get AmountOfSubstance in DecipoundMoles. + /// + public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); + + /// + /// Get AmountOfSubstance in Kilomoles. + /// + public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); + + /// + /// Get AmountOfSubstance in KilopoundMoles. + /// + public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); + + /// + /// Get AmountOfSubstance in Megamoles. + /// + public double Megamoles => As(AmountOfSubstanceUnit.Megamole); + + /// + /// Get AmountOfSubstance in Micromoles. + /// + public double Micromoles => As(AmountOfSubstanceUnit.Micromole); + + /// + /// Get AmountOfSubstance in MicropoundMoles. + /// + public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); + + /// + /// Get AmountOfSubstance in Millimoles. + /// + public double Millimoles => As(AmountOfSubstanceUnit.Millimole); + + /// + /// Get AmountOfSubstance in MillipoundMoles. + /// + public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); + + /// + /// Get AmountOfSubstance in Moles. + /// + public double Moles => As(AmountOfSubstanceUnit.Mole); + + /// + /// Get AmountOfSubstance in Nanomoles. + /// + public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); + + /// + /// Get AmountOfSubstance in NanopoundMoles. + /// + public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); + + /// + /// Get AmountOfSubstance in PoundMoles. + /// + public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AmountOfSubstance from Centimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromCentimoles(double centimoles) + { + double value = (double) centimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); + } + /// + /// Get AmountOfSubstance from CentipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) + { + double value = (double) centipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); + } + /// + /// Get AmountOfSubstance from Decimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromDecimoles(double decimoles) + { + double value = (double) decimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); + } + /// + /// Get AmountOfSubstance from DecipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) + { + double value = (double) decipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); + } + /// + /// Get AmountOfSubstance from Kilomoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromKilomoles(double kilomoles) + { + double value = (double) kilomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); + } + /// + /// Get AmountOfSubstance from KilopoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) + { + double value = (double) kilopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); + } + /// + /// Get AmountOfSubstance from Megamoles. + /// + /// 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); + } + /// + /// Get AmountOfSubstance from Micromoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMicromoles(double micromoles) + { + double value = (double) micromoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); + } + /// + /// Get AmountOfSubstance from MicropoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) + { + double value = (double) micropoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); + } + /// + /// Get AmountOfSubstance from Millimoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMillimoles(double millimoles) + { + double value = (double) millimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); + } + /// + /// Get AmountOfSubstance from MillipoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) + { + double value = (double) millipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); + } + /// + /// Get AmountOfSubstance from Moles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromMoles(double moles) + { + double value = (double) moles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); + } + /// + /// Get AmountOfSubstance from Nanomoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromNanomoles(double nanomoles) + { + double value = (double) nanomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); + } + /// + /// Get AmountOfSubstance from NanopoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) + { + double value = (double) nanopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); + } + /// + /// Get AmountOfSubstance from PoundMoles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmountOfSubstance FromPoundMoles(double poundmoles) + { + double value = (double) poundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +456,367 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] str /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AmountOfSubstance Parse(string str, [CanBeNull] string cultureName) + public static AmountOfSubstance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AmountOfSubstanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMoles(x.Moles + y.Moles)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(AmountOfSubstance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AmountOfSubstanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmountOfSubstanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . + /// + /// A AmountOfSubstance with the specified unit. + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new AmountOfSubstance(convertedValue, unit); + } - if (unit == AmountOfSubstanceUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmountOfSubstanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs index 71328ad967..fd7bcd0813 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AmplitudeRatio + public sealed partial class AmplitudeRatio : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly AmplitudeRatioUnit? _unit; + + static AmplitudeRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit DecibelVolt. /// @@ -75,28 +80,199 @@ public AmplitudeRatio() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private AmplitudeRatio(double numericValue, AmplitudeRatioUnit unit) + { + if(unit == AmplitudeRatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. + /// + public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; + + /// + /// Represents the largest possible value of AmplitudeRatio + /// + public static AmplitudeRatio MaxValue => new AmplitudeRatio(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AmplitudeRatio + /// + public static AmplitudeRatio MinValue => new AmplitudeRatio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AmplitudeRatio; + + /// + /// All units of measurement for the AmplitudeRatio quantity. + /// + public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. + /// + public static AmplitudeRatio Zero => new AmplitudeRatio(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmplitudeRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AmplitudeRatio in DecibelMicrovolts. + /// + public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); + + /// + /// Get AmplitudeRatio in DecibelMillivolts. + /// + public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); + + /// + /// Get AmplitudeRatio in DecibelsUnloaded. + /// + public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); + + /// + /// Get AmplitudeRatio in DecibelVolts. + /// + public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get AmplitudeRatio from DecibelMicrovolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) + { + double value = (double) decibelmicrovolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); + } + /// + /// Get AmplitudeRatio from DecibelMillivolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) + { + double value = (double) decibelmillivolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); + } + /// + /// Get AmplitudeRatio from DecibelsUnloaded. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) + { + double value = (double) decibelsunloaded; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); + } + /// + /// Get AmplitudeRatio from DecibelVolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AmplitudeRatio FromDecibelVolts(double decibelvolts) + { + double value = (double) decibelvolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +291,345 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AmplitudeRatio Parse(string str, [CanBeNull] string cultureName) + public static AmplitudeRatio Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AmplitudeRatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibelVolts(x.DecibelVolts + y.DecibelVolts)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(AmplitudeRatio); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AmplitudeRatioUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == AmplitudeRatioUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmplitudeRatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . + /// + /// A AmplitudeRatio with the specified unit. + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new AmplitudeRatio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmplitudeRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs index 9300463407..00d0b13620 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Angle + public sealed partial class Angle : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AngleUnit? _unit; + static Angle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit Degree. /// @@ -75,28 +80,349 @@ public Angle() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Angle(double numericValue, AngleUnit unit) + { + if(unit == AngleUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Angle, which is Degree. All conversions go via this value. + /// + public static AngleUnit BaseUnit => AngleUnit.Degree; + + /// + /// Represents the largest possible value of Angle + /// + public static Angle MaxValue => new Angle(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Angle + /// + public static Angle MinValue => new Angle(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Angle; + + /// + /// All units of measurement for the Angle quantity. + /// + public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Degree. + /// + public static Angle Zero => new Angle(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Angle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Angle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Angle in Arcminutes. + /// + public double Arcminutes => As(AngleUnit.Arcminute); + + /// + /// Get Angle in Arcseconds. + /// + public double Arcseconds => As(AngleUnit.Arcsecond); + + /// + /// Get Angle in Centiradians. + /// + public double Centiradians => As(AngleUnit.Centiradian); + + /// + /// Get Angle in Deciradians. + /// + public double Deciradians => As(AngleUnit.Deciradian); + + /// + /// Get Angle in Degrees. + /// + public double Degrees => As(AngleUnit.Degree); + + /// + /// Get Angle in Gradians. + /// + public double Gradians => As(AngleUnit.Gradian); + + /// + /// Get Angle in Microdegrees. + /// + public double Microdegrees => As(AngleUnit.Microdegree); + + /// + /// Get Angle in Microradians. + /// + public double Microradians => As(AngleUnit.Microradian); + + /// + /// Get Angle in Millidegrees. + /// + public double Millidegrees => As(AngleUnit.Millidegree); + + /// + /// Get Angle in Milliradians. + /// + public double Milliradians => As(AngleUnit.Milliradian); + + /// + /// Get Angle in Nanodegrees. + /// + public double Nanodegrees => As(AngleUnit.Nanodegree); + + /// + /// Get Angle in Nanoradians. + /// + public double Nanoradians => As(AngleUnit.Nanoradian); + + /// + /// Get Angle in Radians. + /// + public double Radians => As(AngleUnit.Radian); + + /// + /// Get Angle in Revolutions. + /// + public double Revolutions => As(AngleUnit.Revolution); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AngleUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(AngleUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get Angle from Arcminutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromArcminutes(double arcminutes) + { + double value = (double) arcminutes; + return new Angle(value, AngleUnit.Arcminute); + } + /// + /// Get Angle from Arcseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromArcseconds(double arcseconds) + { + double value = (double) arcseconds; + return new Angle(value, AngleUnit.Arcsecond); + } + /// + /// Get Angle from Centiradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromCentiradians(double centiradians) + { + double value = (double) centiradians; + return new Angle(value, AngleUnit.Centiradian); + } + /// + /// Get Angle from Deciradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromDeciradians(double deciradians) + { + double value = (double) deciradians; + return new Angle(value, AngleUnit.Deciradian); + } + /// + /// Get Angle from Degrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromDegrees(double degrees) + { + double value = (double) degrees; + return new Angle(value, AngleUnit.Degree); + } + /// + /// Get Angle from Gradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromGradians(double gradians) + { + double value = (double) gradians; + return new Angle(value, AngleUnit.Gradian); + } + /// + /// Get Angle from Microdegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMicrodegrees(double microdegrees) + { + double value = (double) microdegrees; + return new Angle(value, AngleUnit.Microdegree); } + /// + /// Get Angle from Microradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMicroradians(double microradians) + { + double value = (double) microradians; + return new Angle(value, AngleUnit.Microradian); + } + /// + /// Get Angle from Millidegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMillidegrees(double millidegrees) + { + double value = (double) millidegrees; + return new Angle(value, AngleUnit.Millidegree); + } + /// + /// Get Angle from Milliradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromMilliradians(double milliradians) + { + double value = (double) milliradians; + return new Angle(value, AngleUnit.Milliradian); + } + /// + /// Get Angle from Nanodegrees. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromNanodegrees(double nanodegrees) + { + double value = (double) nanodegrees; + return new Angle(value, AngleUnit.Nanodegree); + } + /// + /// Get Angle from Nanoradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromNanoradians(double nanoradians) + { + double value = (double) nanoradians; + return new Angle(value, AngleUnit.Nanoradian); + } + /// + /// Get Angle from Radians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromRadians(double radians) + { + double value = (double) radians; + return new Angle(value, AngleUnit.Radian); + } + /// + /// Get Angle from Revolutions. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Angle FromRevolutions(double revolutions) + { + double value = (double) revolutions; + return new Angle(value, AngleUnit.Revolution); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Angle unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Angle From(double value, AngleUnit fromUnit) + { + return new Angle((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +441,365 @@ public static string GetAbbreviation(AngleUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Angle Parse(string str, [CanBeNull] string cultureName) + public static Angle Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AngleUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegrees(x.Degrees + y.Degrees)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Angle); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AngleUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AngleUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AngleUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Angle to another Angle with the unit representation . + /// + /// A Angle with the specified unit. + public Angle ToUnit(AngleUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Angle(convertedValue, unit); + } - if (unit == AngleUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AngleUnit.Arcminute: return _value/60; + case AngleUnit.Arcsecond: return _value/3600; + case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; + case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; + case AngleUnit.Degree: return _value; + case AngleUnit.Gradian: return _value*0.9; + case AngleUnit.Microdegree: return (_value) * 1e-6d; + case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; + case AngleUnit.Millidegree: return (_value) * 1e-3d; + case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; + case AngleUnit.Nanodegree: return (_value) * 1e-9d; + case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; + case AngleUnit.Radian: return _value*180/Math.PI; + case AngleUnit.Revolution: return _value*360; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(AngleUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case AngleUnit.Arcminute: return baseUnitValue*60; + case AngleUnit.Arcsecond: return baseUnitValue*3600; + case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; + case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; + case AngleUnit.Degree: return baseUnitValue; + case AngleUnit.Gradian: return baseUnitValue/0.9; + case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; + case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; + case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; + case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; + case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; + case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; + case AngleUnit.Radian: return baseUnitValue/180*Math.PI; + case AngleUnit.Revolution: return baseUnitValue/360; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AngleUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs index 44e60f0419..cbc5a659c1 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ApparentEnergy + public sealed partial class ApparentEnergy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentEnergyUnit? _unit; + + static ApparentEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit VoltampereHour. /// @@ -75,28 +80,184 @@ public ApparentEnergy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ApparentEnergy(double numericValue, ApparentEnergyUnit unit) + { + if(unit == ApparentEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. + /// + public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; + + /// + /// Represents the largest possible value of ApparentEnergy + /// + public static ApparentEnergy MaxValue => new ApparentEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ApparentEnergy + /// + public static ApparentEnergy MinValue => new ApparentEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ApparentEnergy; + + /// + /// All units of measurement for the ApparentEnergy quantity. + /// + public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. + /// + public static ApparentEnergy Zero => new ApparentEnergy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ApparentEnergy in KilovoltampereHours. + /// + public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); + + /// + /// Get ApparentEnergy in MegavoltampereHours. + /// + public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); + + /// + /// Get ApparentEnergy in VoltampereHours. + /// + public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ApparentEnergy from KilovoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) + { + double value = (double) kilovoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); + } + /// + /// Get ApparentEnergy from MegavoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) + { + double value = (double) megavoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); + } + /// + /// Get ApparentEnergy from VoltampereHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentEnergy FromVoltampereHours(double voltamperehours) + { + double value = (double) voltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ApparentEnergy unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) + { + return new ApparentEnergy((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ApparentEnergy Parse(string str, [CanBeNull] string cultureName) + public static ApparentEnergy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ApparentEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltampereHours(x.VoltampereHours + y.VoltampereHours)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ApparentEnergy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ApparentEnergyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ApparentEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == ApparentEnergyUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . + /// + /// A ApparentEnergy with the specified unit. + public ApparentEnergy ToUnit(ApparentEnergyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ApparentEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ApparentEnergyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs index 3ccc80c7a9..daaf46e2cd 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ApparentPower + public sealed partial class ApparentPower : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentPowerUnit? _unit; + + static ApparentPower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Voltampere. /// @@ -75,28 +80,199 @@ public ApparentPower() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ApparentPower(double numericValue, ApparentPowerUnit unit) + { + if(unit == ApparentPowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. + /// + public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; + + /// + /// Represents the largest possible value of ApparentPower + /// + public static ApparentPower MaxValue => new ApparentPower(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ApparentPower + /// + public static ApparentPower MinValue => new ApparentPower(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ApparentPower; + + /// + /// All units of measurement for the ApparentPower quantity. + /// + public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. + /// + public static ApparentPower Zero => new ApparentPower(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentPower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentPower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ApparentPower in Gigavoltamperes. + /// + public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); + + /// + /// Get ApparentPower in Kilovoltamperes. + /// + public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); + + /// + /// Get ApparentPower in Megavoltamperes. + /// + public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); + + /// + /// Get ApparentPower in Voltamperes. + /// + public double Voltamperes => As(ApparentPowerUnit.Voltampere); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ApparentPower from Gigavoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromGigavoltamperes(double gigavoltamperes) + { + double value = (double) gigavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); + } + /// + /// Get ApparentPower from Kilovoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromKilovoltamperes(double kilovoltamperes) + { + double value = (double) kilovoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); + } + /// + /// Get ApparentPower from Megavoltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromMegavoltamperes(double megavoltamperes) + { + double value = (double) megavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); + } + /// + /// Get ApparentPower from Voltamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ApparentPower FromVoltamperes(double voltamperes) + { + double value = (double) voltamperes; + return new ApparentPower(value, ApparentPowerUnit.Voltampere); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +291,345 @@ public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ApparentPower Parse(string str, [CanBeNull] string cultureName) + public static ApparentPower Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ApparentPowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltamperes(x.Voltamperes + y.Voltamperes)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ApparentPower); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ApparentPowerUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ApparentPowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == ApparentPowerUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentPowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ApparentPower to another ApparentPower with the unit representation . + /// + /// A ApparentPower with the specified unit. + public ApparentPower ToUnit(ApparentPowerUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ApparentPower(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentPowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ApparentPowerUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs index 1a618f6b96..a586b76c29 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Area + public sealed partial class Area : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaUnit? _unit; + + static Area() + { + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit SquareMeter. /// @@ -75,28 +80,334 @@ public Area() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Area(double numericValue, AreaUnit unit) + { + if(unit == AreaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Area, which is SquareMeter. All conversions go via this value. + /// + public static AreaUnit BaseUnit => AreaUnit.SquareMeter; + + /// + /// Represents the largest possible value of Area + /// + public static Area MaxValue => new Area(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Area + /// + public static Area MinValue => new Area(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Area; + + /// + /// All units of measurement for the Area quantity. + /// + public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// + public static Area Zero => new Area(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Area.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Area.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Area in Acres. + /// + public double Acres => As(AreaUnit.Acre); + + /// + /// Get Area in Hectares. + /// + public double Hectares => As(AreaUnit.Hectare); + + /// + /// Get Area in SquareCentimeters. + /// + public double SquareCentimeters => As(AreaUnit.SquareCentimeter); + + /// + /// Get Area in SquareDecimeters. + /// + public double SquareDecimeters => As(AreaUnit.SquareDecimeter); + + /// + /// Get Area in SquareFeet. + /// + public double SquareFeet => As(AreaUnit.SquareFoot); + + /// + /// Get Area in SquareInches. + /// + public double SquareInches => As(AreaUnit.SquareInch); + + /// + /// Get Area in SquareKilometers. + /// + public double SquareKilometers => As(AreaUnit.SquareKilometer); + + /// + /// Get Area in SquareMeters. + /// + public double SquareMeters => As(AreaUnit.SquareMeter); + + /// + /// Get Area in SquareMicrometers. + /// + public double SquareMicrometers => As(AreaUnit.SquareMicrometer); + + /// + /// Get Area in SquareMiles. + /// + public double SquareMiles => As(AreaUnit.SquareMile); + + /// + /// Get Area in SquareMillimeters. + /// + public double SquareMillimeters => As(AreaUnit.SquareMillimeter); + + /// + /// Get Area in SquareYards. + /// + public double SquareYards => As(AreaUnit.SquareYard); + + /// + /// Get Area in UsSurveySquareFeet. + /// + public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(AreaUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Area from Acres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromAcres(double acres) + { + double value = (double) acres; + return new Area(value, AreaUnit.Acre); + } + /// + /// Get Area from Hectares. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromHectares(double hectares) + { + double value = (double) hectares; + return new Area(value, AreaUnit.Hectare); + } + /// + /// Get Area from SquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareCentimeters(double squarecentimeters) + { + double value = (double) squarecentimeters; + return new Area(value, AreaUnit.SquareCentimeter); + } + /// + /// Get Area from SquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareDecimeters(double squaredecimeters) + { + double value = (double) squaredecimeters; + return new Area(value, AreaUnit.SquareDecimeter); + } + /// + /// Get Area from SquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareFeet(double squarefeet) + { + double value = (double) squarefeet; + return new Area(value, AreaUnit.SquareFoot); + } + /// + /// Get Area from SquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareInches(double squareinches) + { + double value = (double) squareinches; + return new Area(value, AreaUnit.SquareInch); + } + /// + /// Get Area from SquareKilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareKilometers(double squarekilometers) + { + double value = (double) squarekilometers; + return new Area(value, AreaUnit.SquareKilometer); + } + /// + /// Get Area from SquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMeters(double squaremeters) + { + double value = (double) squaremeters; + return new Area(value, AreaUnit.SquareMeter); + } + /// + /// Get Area from SquareMicrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMicrometers(double squaremicrometers) + { + double value = (double) squaremicrometers; + return new Area(value, AreaUnit.SquareMicrometer); + } + /// + /// Get Area from SquareMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMiles(double squaremiles) + { + double value = (double) squaremiles; + return new Area(value, AreaUnit.SquareMile); + } + /// + /// Get Area from SquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareMillimeters(double squaremillimeters) + { + double value = (double) squaremillimeters; + return new Area(value, AreaUnit.SquareMillimeter); + } + /// + /// Get Area from SquareYards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromSquareYards(double squareyards) + { + double value = (double) squareyards; + return new Area(value, AreaUnit.SquareYard); + } + /// + /// Get Area from UsSurveySquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) + { + double value = (double) ussurveysquarefeet; + return new Area(value, AreaUnit.UsSurveySquareFoot); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +426,363 @@ public static string GetAbbreviation(AreaUnit unit, [CanBeNull] string cultureNa /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Area Parse(string str, [CanBeNull] string cultureName) + public static Area Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMeters(x.SquareMeters + y.SquareMeters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Area); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AreaUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AreaUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to 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."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == AreaUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Area. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Area to another Area with the unit representation . + /// + /// A Area with the specified unit. + public Area ToUnit(AreaUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Area(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AreaUnit.Acre: return _value*4046.85642; + case AreaUnit.Hectare: return _value*1e4; + case AreaUnit.SquareCentimeter: return _value*1e-4; + case AreaUnit.SquareDecimeter: return _value*1e-2; + case AreaUnit.SquareFoot: return _value*0.092903; + case AreaUnit.SquareInch: return _value*0.00064516; + case AreaUnit.SquareKilometer: return _value*1e6; + case AreaUnit.SquareMeter: return _value; + case AreaUnit.SquareMicrometer: return _value*1e-12; + case AreaUnit.SquareMile: return _value*2.59e6; + case AreaUnit.SquareMillimeter: return _value*1e-6; + case AreaUnit.SquareYard: return _value*0.836127; + case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(AreaUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case AreaUnit.Acre: return baseUnitValue/4046.85642; + case AreaUnit.Hectare: return baseUnitValue/1e4; + case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; + case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; + case AreaUnit.SquareFoot: return baseUnitValue/0.092903; + case AreaUnit.SquareInch: return baseUnitValue/0.00064516; + case AreaUnit.SquareKilometer: return baseUnitValue/1e6; + case AreaUnit.SquareMeter: return baseUnitValue; + case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; + case AreaUnit.SquareMile: return baseUnitValue/2.59e6; + case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; + case AreaUnit.SquareYard: return baseUnitValue/0.836127; + case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AreaUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs index 14910ca0b6..10bf58c368 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The area density of a two-dimensional object is calculated as the mass per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AreaDensity + public sealed partial class AreaDensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaDensityUnit? _unit; + + static AreaDensity() + { + BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerSquareMeter. /// @@ -75,28 +80,154 @@ public AreaDensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private AreaDensity(double numericValue, AreaDensityUnit unit) + { + if(unit == AreaDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. + /// + public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; + + /// + /// Represents the largest possible value of AreaDensity + /// + public static AreaDensity MaxValue => new AreaDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AreaDensity + /// + public static AreaDensity MinValue => new AreaDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AreaDensity; + + /// + /// All units of measurement for the AreaDensity quantity. + /// + public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// + public static AreaDensity Zero => new AreaDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaDensity in KilogramsPerSquareMeter. + /// + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get AreaDensity from KilogramsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) + { + double value = (double) kilogramspersquaremeter; + return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +246,339 @@ public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AreaDensity Parse(string str, [CanBeNull] string cultureName) + public static AreaDensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerSquareMeter(x.KilogramsPerSquareMeter + y.KilogramsPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(AreaDensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AreaDensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AreaDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == AreaDensityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AreaDensityUnit.KilogramPerSquareMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(AreaDensityUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AreaDensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs index eef219081f..88e609fde3 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// A geometric property of an area that reflects how its points are distributed with regard to an axis. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AreaMomentOfInertia + public sealed partial class AreaMomentOfInertia : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaMomentOfInertiaUnit? _unit; + static AreaMomentOfInertia() + { + BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit MeterToTheFourth. /// @@ -75,28 +80,229 @@ public AreaMomentOfInertia() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private AreaMomentOfInertia(double numericValue, AreaMomentOfInertiaUnit unit) + { + if(unit == AreaMomentOfInertiaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. + /// + public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; + + /// + /// Represents the largest possible value of AreaMomentOfInertia + /// + public static AreaMomentOfInertia MaxValue => new AreaMomentOfInertia(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AreaMomentOfInertia + /// + public static AreaMomentOfInertia MinValue => new AreaMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; + + /// + /// All units of measurement for the AreaMomentOfInertia quantity. + /// + public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. + /// + public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaMomentOfInertia in CentimetersToTheFourth. + /// + public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in DecimetersToTheFourth. + /// + public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in FeetToTheFourth. + /// + public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); + + /// + /// Get AreaMomentOfInertia in InchesToTheFourth. + /// + public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); + + /// + /// Get AreaMomentOfInertia in MetersToTheFourth. + /// + public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in MillimetersToTheFourth. + /// + public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get AreaMomentOfInertia from CentimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) + { + double value = (double) centimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from DecimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) + { + double value = (double) decimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); } + /// + /// Get AreaMomentOfInertia from FeetToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) + { + double value = (double) feettothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); + } + /// + /// Get AreaMomentOfInertia from InchesToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) + { + double value = (double) inchestothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) + { + double value = (double) meterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MillimetersToTheFourth. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) + { + double value = (double) millimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// AreaMomentOfInertia unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) + { + return new AreaMomentOfInertia((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +321,349 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AreaMomentOfInertia Parse(string str, [CanBeNull] string cultureName) + public static AreaMomentOfInertia Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaMomentOfInertiaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersToTheFourth(x.MetersToTheFourth + y.MetersToTheFourth)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(AreaMomentOfInertia); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static AreaMomentOfInertiaUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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); + } - if (unit == AreaMomentOfInertiaUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaMomentOfInertiaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . + /// + /// A AreaMomentOfInertia with the specified unit. + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new AreaMomentOfInertia(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs index 3a5e50f278..9f94b2b184 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class BitRate : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BitRateUnit? _unit; + static BitRate() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit BitPerSecond. /// @@ -75,28 +83,529 @@ public BitRate() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private BitRate(decimal numericValue, BitRateUnit unit) + { + if(unit == BitRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. + /// + public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; + + /// + /// Represents the largest possible value of BitRate + /// + public static BitRate MaxValue => new BitRate(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of BitRate + /// + public static BitRate MinValue => new BitRate(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.BitRate; + + /// + /// All units of measurement for the BitRate quantity. + /// + public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. + /// + public static BitRate Zero => new BitRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BitRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BitRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get BitRate in BitsPerSecond. + /// + public double BitsPerSecond => As(BitRateUnit.BitPerSecond); + + /// + /// Get BitRate in BytesPerSecond. + /// + public double BytesPerSecond => As(BitRateUnit.BytePerSecond); + + /// + /// Get BitRate in ExabitsPerSecond. + /// + public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + + /// + /// Get BitRate in ExabytesPerSecond. + /// + public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + + /// + /// Get BitRate in ExbibitsPerSecond. + /// + public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + + /// + /// Get BitRate in ExbibytesPerSecond. + /// + public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + + /// + /// Get BitRate in GibibitsPerSecond. + /// + public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + + /// + /// Get BitRate in GibibytesPerSecond. + /// + public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + + /// + /// Get BitRate in GigabitsPerSecond. + /// + public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + + /// + /// Get BitRate in GigabytesPerSecond. + /// + public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + + /// + /// Get BitRate in KibibitsPerSecond. + /// + public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + + /// + /// Get BitRate in KibibytesPerSecond. + /// + public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + + /// + /// Get BitRate in KilobitsPerSecond. + /// + public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + + /// + /// Get BitRate in KilobytesPerSecond. + /// + public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + + /// + /// Get BitRate in MebibitsPerSecond. + /// + public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + + /// + /// Get BitRate in MebibytesPerSecond. + /// + public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + + /// + /// Get BitRate in MegabitsPerSecond. + /// + public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + + /// + /// Get BitRate in MegabytesPerSecond. + /// + public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + + /// + /// Get BitRate in PebibitsPerSecond. + /// + public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + + /// + /// Get BitRate in PebibytesPerSecond. + /// + public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + + /// + /// Get BitRate in PetabitsPerSecond. + /// + public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + + /// + /// Get BitRate in PetabytesPerSecond. + /// + public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + + /// + /// Get BitRate in TebibitsPerSecond. + /// + public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + + /// + /// Get BitRate in TebibytesPerSecond. + /// + public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + + /// + /// Get BitRate in TerabitsPerSecond. + /// + public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + + /// + /// Get BitRate in TerabytesPerSecond. + /// + public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BitRateUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get BitRate from BitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromBitsPerSecond(double bitspersecond) + { + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); + } + /// + /// Get BitRate from BytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromBytesPerSecond(double bytespersecond) + { + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); + } + /// + /// Get BitRate from ExabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExabitsPerSecond(double exabitspersecond) + { + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); + } + /// + /// Get BitRate from ExabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExabytesPerSecond(double exabytespersecond) + { + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); + } + /// + /// Get BitRate from ExbibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExbibitsPerSecond(double exbibitspersecond) + { + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); + } + /// + /// Get BitRate from ExbibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromExbibytesPerSecond(double exbibytespersecond) + { + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); + } + /// + /// Get BitRate from GibibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGibibitsPerSecond(double gibibitspersecond) + { + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); + } + /// + /// Get BitRate from GibibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGibibytesPerSecond(double gibibytespersecond) + { + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); + } + /// + /// Get BitRate from GigabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGigabitsPerSecond(double gigabitspersecond) + { + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); + } + /// + /// Get BitRate from GigabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromGigabytesPerSecond(double gigabytespersecond) + { + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); + } + /// + /// Get BitRate from KibibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKibibitsPerSecond(double kibibitspersecond) + { + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); + } + /// + /// Get BitRate from KibibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKibibytesPerSecond(double kibibytespersecond) + { + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); + } + /// + /// Get BitRate from KilobitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKilobitsPerSecond(double kilobitspersecond) + { + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); + } + /// + /// Get BitRate from KilobytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromKilobytesPerSecond(double kilobytespersecond) + { + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); + } + /// + /// Get BitRate from MebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMebibitsPerSecond(double mebibitspersecond) + { + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); + } + /// + /// Get BitRate from MebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMebibytesPerSecond(double mebibytespersecond) + { + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); + } + /// + /// Get BitRate from MegabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMegabitsPerSecond(double megabitspersecond) + { + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); + } + /// + /// Get BitRate from MegabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromMegabytesPerSecond(double megabytespersecond) + { + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); + } + /// + /// Get BitRate from PebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPebibitsPerSecond(double pebibitspersecond) + { + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); + } + /// + /// Get BitRate from PebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPebibytesPerSecond(double pebibytespersecond) + { + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); + } + /// + /// Get BitRate from PetabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPetabitsPerSecond(double petabitspersecond) + { + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); + } + /// + /// Get BitRate from PetabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromPetabytesPerSecond(double petabytespersecond) + { + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); + } + /// + /// Get BitRate from TebibitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTebibitsPerSecond(double tebibitspersecond) + { + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); + } + /// + /// Get BitRate from TebibytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTebibytesPerSecond(double tebibytespersecond) + { + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); + } + /// + /// Get BitRate from TerabitsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTerabitsPerSecond(double terabitspersecond) + { + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); + } + /// + /// Get BitRate from TerabytesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BitRate FromTerabytesPerSecond(double terabytespersecond) + { + decimal value = (decimal) terabytespersecond; + return new BitRate(value, BitRateUnit.TerabytePerSecond); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// BitRate unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static BitRate From(double value, BitRateUnit fromUnit) + { + return new BitRate((decimal)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +624,389 @@ public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] string cultur /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static BitRate Parse(string str, [CanBeNull] string cultureName) + public static BitRate Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - BitRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromBitsPerSecond(x.BitsPerSecond + y.BitsPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(BitRate); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static BitRateUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static BitRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out BitRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == BitRateUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BitRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this BitRate to another BitRate with the unit representation . + /// + /// A BitRate with the specified unit. + public BitRate ToUnit(BitRateUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new BitRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BitRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(BitRateUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs index cb392121fb..7951122f05 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class BrakeSpecificFuelConsumption + public sealed partial class BrakeSpecificFuelConsumption : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + static BrakeSpecificFuelConsumption() + { + BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerJoule. /// @@ -75,28 +80,184 @@ public BrakeSpecificFuelConsumption() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private BrakeSpecificFuelConsumption(double numericValue, BrakeSpecificFuelConsumptionUnit unit) + { + if(unit == BrakeSpecificFuelConsumptionUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. + /// + public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + + /// + /// Represents the largest possible value of BrakeSpecificFuelConsumption + /// + public static BrakeSpecificFuelConsumption MaxValue => new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of BrakeSpecificFuelConsumption + /// + public static BrakeSpecificFuelConsumption MinValue => new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; + + /// + /// All units of measurement for the BrakeSpecificFuelConsumption quantity. + /// + public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. + /// + public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get BrakeSpecificFuelConsumption in GramsPerKiloWattHour. + /// + public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + + /// + /// Get BrakeSpecificFuelConsumption in KilogramsPerJoule. + /// + public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + + /// + /// Get BrakeSpecificFuelConsumption in PoundsPerMechanicalHorsepowerHour. + /// + public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) + { + double value = (double) gramsperkilowatthour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + } + /// + /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) + { + double value = (double) kilogramsperjoule; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + } + /// + /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) + { + double value = (double) poundspermechanicalhorsepowerhour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// BrakeSpecificFuelConsumption unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) + { + return new BrakeSpecificFuelConsumption((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [Can /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] string cultureName) + public static BrakeSpecificFuelConsumption Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - BrakeSpecificFuelConsumptionUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerJoule(x.KilogramsPerJoule + y.KilogramsPerJoule)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(BrakeSpecificFuelConsumption); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BrakeSpecificFuelConsumptionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . + /// + /// A BrakeSpecificFuelConsumption with the specified unit. + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new BrakeSpecificFuelConsumption(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BrakeSpecificFuelConsumptionUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs index 673e10abbd..6892b0688d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Capacitance is the ability of a body to store an electric charge. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Capacitance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CapacitanceUnit? _unit; + static Capacitance() + { + BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Farad. /// @@ -75,28 +83,214 @@ public Capacitance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Capacitance(double numericValue, CapacitanceUnit unit) + { + if(unit == CapacitanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Capacitance, which is Farad. All conversions go via this value. + /// + public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; + + /// + /// Represents the largest possible value of Capacitance + /// + public static Capacitance MaxValue => new Capacitance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Capacitance + /// + public static Capacitance MinValue => new Capacitance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Capacitance; + + /// + /// All units of measurement for the Capacitance quantity. + /// + public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Farad. + /// + public static Capacitance Zero => new Capacitance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Capacitance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Capacitance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Capacitance in Farads. + /// + public double Farads => As(CapacitanceUnit.Farad); + + /// + /// Get Capacitance in Microfarads. + /// + public double Microfarads => As(CapacitanceUnit.Microfarad); + + /// + /// Get Capacitance in Millifarads. + /// + public double Millifarads => As(CapacitanceUnit.Millifarad); + + /// + /// Get Capacitance in Nanofarads. + /// + public double Nanofarads => As(CapacitanceUnit.Nanofarad); + + /// + /// Get Capacitance in Picofarads. + /// + public double Picofarads => As(CapacitanceUnit.Picofarad); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CapacitanceUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get Capacitance from Farads. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Capacitance FromFarads(double farads) + { + double value = (double) farads; + return new Capacitance(value, CapacitanceUnit.Farad); + } + /// + /// Get Capacitance from Microfarads. + /// + /// 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); + } + /// + /// Get Capacitance from Millifarads. + /// + /// 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); + } + /// + /// Get Capacitance from Nanofarads. + /// + /// 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); } + /// + /// Get Capacitance from Picofarads. + /// + /// 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 Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +309,347 @@ public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Capacitance Parse(string str, [CanBeNull] string cultureName) + public static Capacitance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - CapacitanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromFarads(x.Farads + y.Farads)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Capacitance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static CapacitanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static CapacitanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is Capacitance objCapacitance)) + return false; - if (unit == CapacitanceUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CapacitanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Capacitance to another Capacitance with the unit representation . + /// + /// A Capacitance with the specified unit. + public Capacitance ToUnit(CapacitanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Capacitance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CapacitanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case CapacitanceUnit.Farad: return _value; + 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."); } + } - return unit; + private double AsBaseNumericType(CapacitanceUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case CapacitanceUnit.Farad: return baseUnitValue; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(CapacitanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs index d87994cf13..5fbf89f4fa 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// A unit that represents a fractional change in size in response to a change in temperature. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class CoefficientOfThermalExpansion + public sealed partial class CoefficientOfThermalExpansion : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly CoefficientOfThermalExpansionUnit? _unit; + + static CoefficientOfThermalExpansion() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit InverseKelvin. /// @@ -75,28 +80,184 @@ public CoefficientOfThermalExpansion() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private CoefficientOfThermalExpansion(double numericValue, CoefficientOfThermalExpansionUnit unit) + { + if(unit == CoefficientOfThermalExpansionUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. + /// + public static CoefficientOfThermalExpansionUnit BaseUnit => CoefficientOfThermalExpansionUnit.InverseKelvin; + + /// + /// Represents the largest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MaxValue => new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MinValue => new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.CoefficientOfThermalExpansion; + + /// + /// All units of measurement for the CoefficientOfThermalExpansion quantity. + /// + public static CoefficientOfThermalExpansionUnit[] Units { get; } = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. + /// + public static CoefficientOfThermalExpansion Zero => new CoefficientOfThermalExpansion(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeCelsius. + /// + public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeFahrenheit. + /// + public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + + /// + /// Get CoefficientOfThermalExpansion in InverseKelvin. + /// + public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(double inversedegreecelsius) + { + double value = (double) inversedegreecelsius; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + } + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(double inversedegreefahrenheit) + { + double value = (double) inversedegreefahrenheit; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + } + /// + /// Get CoefficientOfThermalExpansion from InverseKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static CoefficientOfThermalExpansion FromInverseKelvin(double inversekelvin) + { + double value = (double) inversekelvin; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// CoefficientOfThermalExpansion unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static CoefficientOfThermalExpansion From(double value, CoefficientOfThermalExpansionUnit fromUnit) + { + return new CoefficientOfThermalExpansion((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [Ca /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static CoefficientOfThermalExpansion Parse(string str, [CanBeNull] string cultureName) + public static CoefficientOfThermalExpansion Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - CoefficientOfThermalExpansionUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromInverseKelvin(x.InverseKelvin + y.InverseKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(CoefficientOfThermalExpansion); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static CoefficientOfThermalExpansionUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static CoefficientOfThermalExpansionUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == CoefficientOfThermalExpansionUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . + /// + /// A CoefficientOfThermalExpansion with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new CoefficientOfThermalExpansion(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CoefficientOfThermalExpansionUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*5/9; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*9/5; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs index b36da8240a..ef5d5855f4 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Density : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DensityUnit? _unit; + static Density() + { + BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerCubicMeter. /// @@ -75,28 +83,709 @@ public Density() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Density(double numericValue, DensityUnit unit) + { + if(unit == DensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. + /// + public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; + + /// + /// Represents the largest possible value of Density + /// + public static Density MaxValue => new Density(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Density + /// + public static Density MinValue => new Density(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Density; + + /// + /// All units of measurement for the Density quantity. + /// + public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// + public static Density Zero => new Density(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Density.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Density.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Density in CentigramsPerDeciLiter. + /// + public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); + + /// + /// Get Density in CentigramsPerLiter. + /// + public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); + + /// + /// Get Density in CentigramsPerMilliliter. + /// + public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); + + /// + /// Get Density in DecigramsPerDeciLiter. + /// + public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); + + /// + /// Get Density in DecigramsPerLiter. + /// + public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); + + /// + /// Get Density in DecigramsPerMilliliter. + /// + public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); + + /// + /// Get Density in GramsPerCubicCentimeter. + /// + public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); + + /// + /// Get Density in GramsPerCubicMeter. + /// + public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); + + /// + /// Get Density in GramsPerCubicMillimeter. + /// + public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); + + /// + /// Get Density in GramsPerDeciLiter. + /// + public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); + + /// + /// Get Density in GramsPerLiter. + /// + public double GramsPerLiter => As(DensityUnit.GramPerLiter); + + /// + /// Get Density in GramsPerMilliliter. + /// + public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); + + /// + /// Get Density in KilogramsPerCubicCentimeter. + /// + public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); + + /// + /// Get Density in KilogramsPerCubicMeter. + /// + public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); + + /// + /// Get Density in KilogramsPerCubicMillimeter. + /// + public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); + + /// + /// Get Density in KilopoundsPerCubicFoot. + /// + public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); + + /// + /// Get Density in KilopoundsPerCubicInch. + /// + public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); + + /// + /// Get Density in MicrogramsPerDeciLiter. + /// + public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); + + /// + /// Get Density in MicrogramsPerLiter. + /// + public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); + + /// + /// Get Density in MicrogramsPerMilliliter. + /// + public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); + + /// + /// Get Density in MilligramsPerCubicMeter. + /// + public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); + + /// + /// Get Density in MilligramsPerDeciLiter. + /// + public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); + + /// + /// Get Density in MilligramsPerLiter. + /// + public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); + + /// + /// Get Density in MilligramsPerMilliliter. + /// + public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); + + /// + /// Get Density in NanogramsPerDeciLiter. + /// + public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); + + /// + /// Get Density in NanogramsPerLiter. + /// + public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); + + /// + /// Get Density in NanogramsPerMilliliter. + /// + public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); + + /// + /// Get Density in PicogramsPerDeciLiter. + /// + public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); + + /// + /// Get Density in PicogramsPerLiter. + /// + public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); + + /// + /// Get Density in PicogramsPerMilliliter. + /// + public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); + + /// + /// Get Density in PoundsPerCubicFoot. + /// + public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); + + /// + /// Get Density in PoundsPerCubicInch. + /// + public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); + + /// + /// Get Density in PoundsPerImperialGallon. + /// + public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); + + /// + /// Get Density in PoundsPerUSGallon. + /// + public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); + + /// + /// Get Density in SlugsPerCubicFoot. + /// + public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); + + /// + /// Get Density in TonnesPerCubicCentimeter. + /// + public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); + + /// + /// Get Density in TonnesPerCubicMeter. + /// + public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); + + /// + /// Get Density in TonnesPerCubicMillimeter. + /// + public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(DensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get Density from CentigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) + { + double value = (double) centigramsperdeciliter; + return new Density(value, DensityUnit.CentigramPerDeciliter); } + /// + /// Get Density from CentigramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerLiter(double centigramsperliter) + { + double value = (double) centigramsperliter; + return new Density(value, DensityUnit.CentigramPerLiter); + } + /// + /// Get Density from CentigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) + { + double value = (double) centigramspermilliliter; + return new Density(value, DensityUnit.CentigramPerMilliliter); + } + /// + /// Get Density from DecigramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) + { + double value = (double) decigramsperdeciliter; + return new Density(value, DensityUnit.DecigramPerDeciliter); + } + /// + /// Get Density from DecigramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerLiter(double decigramsperliter) + { + double value = (double) decigramsperliter; + return new Density(value, DensityUnit.DecigramPerLiter); + } + /// + /// Get Density from DecigramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) + { + double value = (double) decigramspermilliliter; + return new Density(value, DensityUnit.DecigramPerMilliliter); + } + /// + /// Get Density from GramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) + { + double value = (double) gramspercubiccentimeter; + return new Density(value, DensityUnit.GramPerCubicCentimeter); + } + /// + /// Get Density from GramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicMeter(double gramspercubicmeter) + { + double value = (double) gramspercubicmeter; + return new Density(value, DensityUnit.GramPerCubicMeter); + } + /// + /// Get Density from GramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) + { + double value = (double) gramspercubicmillimeter; + return new Density(value, DensityUnit.GramPerCubicMillimeter); + } + /// + /// Get Density from GramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerDeciLiter(double gramsperdeciliter) + { + double value = (double) gramsperdeciliter; + return new Density(value, DensityUnit.GramPerDeciliter); + } + /// + /// Get Density from GramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerLiter(double gramsperliter) + { + double value = (double) gramsperliter; + return new Density(value, DensityUnit.GramPerLiter); + } + /// + /// Get Density from GramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromGramsPerMilliliter(double gramspermilliliter) + { + double value = (double) gramspermilliliter; + return new Density(value, DensityUnit.GramPerMilliliter); + } + /// + /// Get Density from KilogramsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) + { + double value = (double) kilogramspercubiccentimeter; + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); + } + /// + /// Get Density from KilogramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) + { + double value = (double) kilogramspercubicmeter; + return new Density(value, DensityUnit.KilogramPerCubicMeter); + } + /// + /// Get Density from KilogramsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) + { + double value = (double) kilogramspercubicmillimeter; + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); + } + /// + /// Get Density from KilopoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) + { + double value = (double) kilopoundspercubicfoot; + return new Density(value, DensityUnit.KilopoundPerCubicFoot); + } + /// + /// Get Density from KilopoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) + { + double value = (double) kilopoundspercubicinch; + return new Density(value, DensityUnit.KilopoundPerCubicInch); + } + /// + /// Get Density from MicrogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) + { + double value = (double) microgramsperdeciliter; + return new Density(value, DensityUnit.MicrogramPerDeciliter); + } + /// + /// Get Density from MicrogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerLiter(double microgramsperliter) + { + double value = (double) microgramsperliter; + return new Density(value, DensityUnit.MicrogramPerLiter); + } + /// + /// Get Density from MicrogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) + { + double value = (double) microgramspermilliliter; + return new Density(value, DensityUnit.MicrogramPerMilliliter); + } + /// + /// Get Density from MilligramsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) + { + double value = (double) milligramspercubicmeter; + return new Density(value, DensityUnit.MilligramPerCubicMeter); + } + /// + /// Get Density from MilligramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) + { + double value = (double) milligramsperdeciliter; + return new Density(value, DensityUnit.MilligramPerDeciliter); + } + /// + /// Get Density from MilligramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerLiter(double milligramsperliter) + { + double value = (double) milligramsperliter; + return new Density(value, DensityUnit.MilligramPerLiter); + } + /// + /// Get Density from MilligramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) + { + double value = (double) milligramspermilliliter; + return new Density(value, DensityUnit.MilligramPerMilliliter); + } + /// + /// Get Density from NanogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) + { + double value = (double) nanogramsperdeciliter; + return new Density(value, DensityUnit.NanogramPerDeciliter); + } + /// + /// Get Density from NanogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerLiter(double nanogramsperliter) + { + double value = (double) nanogramsperliter; + return new Density(value, DensityUnit.NanogramPerLiter); + } + /// + /// Get Density from NanogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) + { + double value = (double) nanogramspermilliliter; + return new Density(value, DensityUnit.NanogramPerMilliliter); + } + /// + /// Get Density from PicogramsPerDeciLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) + { + double value = (double) picogramsperdeciliter; + return new Density(value, DensityUnit.PicogramPerDeciliter); + } + /// + /// Get Density from PicogramsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerLiter(double picogramsperliter) + { + double value = (double) picogramsperliter; + return new Density(value, DensityUnit.PicogramPerLiter); + } + /// + /// Get Density from PicogramsPerMilliliter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) + { + double value = (double) picogramspermilliliter; + return new Density(value, DensityUnit.PicogramPerMilliliter); + } + /// + /// Get Density from PoundsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) + { + double value = (double) poundspercubicfoot; + return new Density(value, DensityUnit.PoundPerCubicFoot); + } + /// + /// Get Density from PoundsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerCubicInch(double poundspercubicinch) + { + double value = (double) poundspercubicinch; + return new Density(value, DensityUnit.PoundPerCubicInch); + } + /// + /// Get Density from PoundsPerImperialGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) + { + double value = (double) poundsperimperialgallon; + return new Density(value, DensityUnit.PoundPerImperialGallon); + } + /// + /// Get Density from PoundsPerUSGallon. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromPoundsPerUSGallon(double poundsperusgallon) + { + double value = (double) poundsperusgallon; + return new Density(value, DensityUnit.PoundPerUSGallon); + } + /// + /// Get Density from SlugsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new Density(value, DensityUnit.SlugPerCubicFoot); + } + /// + /// Get Density from TonnesPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new Density(value, DensityUnit.TonnePerCubicCentimeter); + } + /// + /// Get Density from TonnesPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new Density(value, DensityUnit.TonnePerCubicMeter); + } + /// + /// Get Density from TonnesPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) + { + double value = (double) tonnespercubicmillimeter; + return new Density(value, DensityUnit.TonnePerCubicMillimeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Density unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Density From(double value, DensityUnit fromUnit) + { + return new Density((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +804,413 @@ public static string GetAbbreviation(DensityUnit unit, [CanBeNull] string cultur /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Density Parse(string str, [CanBeNull] string cultureName) + public static Density Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerCubicMeter(x.KilogramsPerCubicMeter + y.KilogramsPerCubicMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Density); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static DensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static DensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is Density objDensity)) + return false; - if (unit == DensityUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Density to another Density with the unit representation . + /// + /// A Density with the specified unit. + public Density ToUnit(DensityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Density(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; + case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; + case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; + case DensityUnit.GramPerCubicMeter: return _value/1e3; + case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; + case DensityUnit.GramPerDeciliter: return _value/1e-1; + case DensityUnit.GramPerLiter: return _value/1; + case DensityUnit.GramPerMilliliter: return _value/1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; + case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; + case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; + case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; + case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; + case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; + case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; + case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return _value*515.378818; + case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; + case DensityUnit.TonnePerCubicMeter: return _value/0.001; + case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(DensityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; + case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; + case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; + case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; + case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; + case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; + case DensityUnit.GramPerLiter: return baseUnitValue*1; + case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; + case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; + case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; + case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; + case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; + case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; + case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; + case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; + case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; + case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; + case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(DensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs index 6629015d75..e57ea85bbd 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Duration + public sealed partial class Duration : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly DurationUnit? _unit; + + static Duration() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Second. /// @@ -75,28 +80,289 @@ public Duration() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Duration(double numericValue, DurationUnit unit) + { + if(unit == DurationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Duration, which is Second. All conversions go via this value. + /// + public static DurationUnit BaseUnit => DurationUnit.Second; + + /// + /// Represents the largest possible value of Duration + /// + public static Duration MaxValue => new Duration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Duration + /// + public static Duration MinValue => new Duration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Duration; + + /// + /// All units of measurement for the Duration quantity. + /// + public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Duration Zero => new Duration(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Duration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Duration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Duration in Days. + /// + public double Days => As(DurationUnit.Day); + + /// + /// Get Duration in Hours. + /// + public double Hours => As(DurationUnit.Hour); + + /// + /// Get Duration in Microseconds. + /// + public double Microseconds => As(DurationUnit.Microsecond); + + /// + /// Get Duration in Milliseconds. + /// + public double Milliseconds => As(DurationUnit.Millisecond); + + /// + /// Get Duration in Minutes. + /// + public double Minutes => As(DurationUnit.Minute); + + /// + /// Get Duration in Months30. + /// + public double Months30 => As(DurationUnit.Month30); + + /// + /// Get Duration in Nanoseconds. + /// + public double Nanoseconds => As(DurationUnit.Nanosecond); + + /// + /// Get Duration in Seconds. + /// + public double Seconds => As(DurationUnit.Second); + + /// + /// Get Duration in Weeks. + /// + public double Weeks => As(DurationUnit.Week); + + /// + /// Get Duration in Years365. + /// + public double Years365 => As(DurationUnit.Year365); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DurationUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(DurationUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get Duration from Days. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromDays(double days) + { + double value = (double) days; + return new Duration(value, DurationUnit.Day); + } + /// + /// Get Duration from Hours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromHours(double hours) + { + double value = (double) hours; + return new Duration(value, DurationUnit.Hour); + } + /// + /// Get Duration from Microseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMicroseconds(double microseconds) + { + double value = (double) microseconds; + return new Duration(value, DurationUnit.Microsecond); + } + /// + /// Get Duration from Milliseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMilliseconds(double milliseconds) + { + double value = (double) milliseconds; + return new Duration(value, DurationUnit.Millisecond); + } + /// + /// Get Duration from Minutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMinutes(double minutes) + { + double value = (double) minutes; + return new Duration(value, DurationUnit.Minute); + } + /// + /// Get Duration from Months30. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromMonths30(double months30) + { + double value = (double) months30; + return new Duration(value, DurationUnit.Month30); + } + /// + /// Get Duration from Nanoseconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromNanoseconds(double nanoseconds) + { + double value = (double) nanoseconds; + return new Duration(value, DurationUnit.Nanosecond); + } + /// + /// Get Duration from Seconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromSeconds(double seconds) + { + double value = (double) seconds; + return new Duration(value, DurationUnit.Second); + } + /// + /// Get Duration from Weeks. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromWeeks(double weeks) + { + double value = (double) weeks; + return new Duration(value, DurationUnit.Week); + } + /// + /// Get Duration from Years365. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Duration FromYears365(double years365) + { + double value = (double) years365; + return new Duration(value, DurationUnit.Year365); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +381,357 @@ public static string GetAbbreviation(DurationUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Duration Parse(string str, [CanBeNull] string cultureName) + public static Duration Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DurationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSeconds(x.Seconds + y.Seconds)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Duration); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static DurationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static DurationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out DurationUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == DurationUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DurationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Duration ToUnit(DurationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Duration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DurationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DurationUnit.Day: return _value*24*3600; + case DurationUnit.Hour: return _value*3600; + case DurationUnit.Microsecond: return (_value) * 1e-6d; + case DurationUnit.Millisecond: return (_value) * 1e-3d; + case DurationUnit.Minute: return _value*60; + case DurationUnit.Month30: return _value*30*24*3600; + case DurationUnit.Nanosecond: return (_value) * 1e-9d; + case DurationUnit.Second: return _value; + case DurationUnit.Week: return _value*7*24*3600; + case DurationUnit.Year365: return _value*365*24*3600; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(DurationUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case DurationUnit.Day: return baseUnitValue/(24*3600); + case DurationUnit.Hour: return baseUnitValue/3600; + case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; + case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; + case DurationUnit.Minute: return baseUnitValue/60; + case DurationUnit.Month30: return baseUnitValue/(30*24*3600); + case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; + case DurationUnit.Second: return baseUnitValue; + case DurationUnit.Week: return baseUnitValue/(7*24*3600); + case DurationUnit.Year365: return baseUnitValue/(365*24*3600); + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(DurationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs index c618b94c4a..20534fd15c 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class DynamicViscosity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DynamicViscosityUnit? _unit; + static DynamicViscosity() + { + BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. /// @@ -75,28 +83,229 @@ public DynamicViscosity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private DynamicViscosity(double numericValue, DynamicViscosityUnit unit) + { + if(unit == DynamicViscosityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. + /// + public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; + + /// + /// Represents the largest possible value of DynamicViscosity + /// + public static DynamicViscosity MaxValue => new DynamicViscosity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of DynamicViscosity + /// + public static DynamicViscosity MinValue => new DynamicViscosity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.DynamicViscosity; + + /// + /// All units of measurement for the DynamicViscosity quantity. + /// + public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// + public static DynamicViscosity Zero => new DynamicViscosity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => DynamicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get DynamicViscosity in Centipoise. + /// + public double Centipoise => As(DynamicViscosityUnit.Centipoise); + + /// + /// Get DynamicViscosity in MicropascalSeconds. + /// + public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); + + /// + /// Get DynamicViscosity in MillipascalSeconds. + /// + public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); + + /// + /// Get DynamicViscosity in NewtonSecondsPerMeterSquared. + /// + public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); + + /// + /// Get DynamicViscosity in PascalSeconds. + /// + public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); + + /// + /// Get DynamicViscosity in Poise. + /// + public double Poise => As(DynamicViscosityUnit.Poise); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DynamicViscosityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get DynamicViscosity from Centipoise. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromCentipoise(double centipoise) + { + double value = (double) centipoise; + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); + } + /// + /// Get DynamicViscosity from MicropascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) + { + double value = (double) micropascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); } + /// + /// Get DynamicViscosity from MillipascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) + { + double value = (double) millipascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); + } + /// + /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) + { + double value = (double) newtonsecondspermetersquared; + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); + } + /// + /// Get DynamicViscosity from PascalSeconds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromPascalSeconds(double pascalseconds) + { + double value = (double) pascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); + } + /// + /// Get DynamicViscosity from Poise. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static DynamicViscosity FromPoise(double poise) + { + double value = (double) poise; + return new DynamicViscosity(value, DynamicViscosityUnit.Poise); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// DynamicViscosity unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) + { + return new DynamicViscosity((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +324,349 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] stri /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static DynamicViscosity Parse(string str, [CanBeNull] string cultureName) + public static DynamicViscosity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DynamicViscosityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonSecondsPerMeterSquared(x.NewtonSecondsPerMeterSquared + y.NewtonSecondsPerMeterSquared)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(DynamicViscosity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static DynamicViscosityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static DynamicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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); + } - if (unit == DynamicViscosityUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DynamicViscosityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . + /// + /// A DynamicViscosity with the specified unit. + public DynamicViscosity ToUnit(DynamicViscosityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new DynamicViscosity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DynamicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; + case DynamicViscosityUnit.PascalSecond: return _value; + case DynamicViscosityUnit.Poise: return _value/10; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(DynamicViscosityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; + case DynamicViscosityUnit.PascalSecond: return baseUnitValue; + case DynamicViscosityUnit.Poise: return baseUnitValue*10; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(DynamicViscosityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs index 9eef04267e..f22a5da97d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricAdmittance + public sealed partial class ElectricAdmittance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricAdmittanceUnit? _unit; + + static ElectricAdmittance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Siemens. /// @@ -75,28 +80,199 @@ public ElectricAdmittance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricAdmittance(double numericValue, ElectricAdmittanceUnit unit) + { + if(unit == ElectricAdmittanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. + /// + public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; + + /// + /// Represents the largest possible value of ElectricAdmittance + /// + public static ElectricAdmittance MaxValue => new ElectricAdmittance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricAdmittance + /// + public static ElectricAdmittance MinValue => new ElectricAdmittance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricAdmittance; + + /// + /// All units of measurement for the ElectricAdmittance quantity. + /// + public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricAdmittance Zero => new ElectricAdmittance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricAdmittance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricAdmittance in Microsiemens. + /// + public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); + + /// + /// Get ElectricAdmittance in Millisiemens. + /// + public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); + + /// + /// Get ElectricAdmittance in Nanosiemens. + /// + public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); + + /// + /// Get ElectricAdmittance in Siemens. + /// + public double Siemens => As(ElectricAdmittanceUnit.Siemens); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ElectricAdmittance from Microsiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromMicrosiemens(double microsiemens) + { + double value = (double) microsiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); + } + /// + /// Get ElectricAdmittance from Millisiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromMillisiemens(double millisiemens) + { + double value = (double) millisiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); + } + /// + /// Get ElectricAdmittance from Nanosiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromNanosiemens(double nanosiemens) + { + double value = (double) nanosiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); + } + /// + /// Get ElectricAdmittance from Siemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricAdmittance FromSiemens(double siemens) + { + double value = (double) siemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +291,345 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] st /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricAdmittance Parse(string str, [CanBeNull] string cultureName) + public static ElectricAdmittance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricAdmittanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemens(x.Siemens + y.Siemens)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricAdmittance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricAdmittanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == ElectricAdmittanceUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricAdmittanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . + /// + /// A ElectricAdmittance with the specified unit. + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricAdmittance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricAdmittanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs index a967b0fd5f..bb6f5726f4 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricCharge : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeUnit? _unit; + + static ElectricCharge() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Coulomb. /// @@ -75,28 +83,154 @@ public ElectricCharge() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricCharge(double numericValue, ElectricChargeUnit unit) + { + if(unit == ElectricChargeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. + /// + public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; + + /// + /// Represents the largest possible value of ElectricCharge + /// + public static ElectricCharge MaxValue => new ElectricCharge(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCharge + /// + public static ElectricCharge MinValue => new ElectricCharge(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCharge; + + /// + /// All units of measurement for the ElectricCharge quantity. + /// + public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. + /// + public static ElectricCharge Zero => new ElectricCharge(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCharge.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCharge in Coulombs. + /// + public double Coulombs => As(ElectricChargeUnit.Coulomb); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCharge from Coulombs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCharge FromCoulombs(double coulombs) + { + double value = (double) coulombs; + return new ElectricCharge(value, ElectricChargeUnit.Coulomb); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCharge Parse(string str, [CanBeNull] string cultureName) + public static ElectricCharge Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricChargeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCoulombs(x.Coulombs + y.Coulombs)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricCharge); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricChargeUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricChargeUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricChargeUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricChargeUnit.Coulomb: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(ElectricChargeUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ElectricChargeUnit.Coulomb: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricChargeUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs index b964325a3e..1bc6aa4bd2 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In electromagnetism, charge density is a measure of the amount of electric charge per unit length, surface area, or volume. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricChargeDensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeDensityUnit? _unit; + + static ElectricChargeDensity() + { + BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit CoulombPerCubicMeter. /// @@ -75,28 +83,154 @@ public ElectricChargeDensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricChargeDensity(double numericValue, ElectricChargeDensityUnit unit) + { + if(unit == ElectricChargeDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. + /// + public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; + + /// + /// Represents the largest possible value of ElectricChargeDensity + /// + public static ElectricChargeDensity MaxValue => new ElectricChargeDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricChargeDensity + /// + public static ElectricChargeDensity MinValue => new ElectricChargeDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricChargeDensity; + + /// + /// All units of measurement for the ElectricChargeDensity quantity. + /// + public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// + public static ElectricChargeDensity Zero => new ElectricChargeDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricChargeDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricChargeDensity in CoulombsPerCubicMeter. + /// + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricChargeDensity from CoulombsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) + { + double value = (double) coulombspercubicmeter; + return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricChargeDensity Parse(string str, [CanBeNull] string cultureName) + public static ElectricChargeDensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricChargeDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCoulombsPerCubicMeter(x.CoulombsPerCubicMeter + y.CoulombsPerCubicMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricChargeDensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricChargeDensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricChargeDensityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs index ec4734b3f5..a8ea454d26 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricConductance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductanceUnit? _unit; + + static ElectricConductance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Siemens. /// @@ -75,28 +83,184 @@ public ElectricConductance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricConductance(double numericValue, ElectricConductanceUnit unit) + { + if(unit == ElectricConductanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. + /// + public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; + + /// + /// Represents the largest possible value of ElectricConductance + /// + public static ElectricConductance MaxValue => new ElectricConductance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricConductance + /// + public static ElectricConductance MinValue => new ElectricConductance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricConductance; + + /// + /// All units of measurement for the ElectricConductance quantity. + /// + public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricConductance Zero => new ElectricConductance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricConductance in Microsiemens. + /// + public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); + + /// + /// Get ElectricConductance in Millisiemens. + /// + public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); + + /// + /// Get ElectricConductance in Siemens. + /// + public double Siemens => As(ElectricConductanceUnit.Siemens); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ElectricConductance from Microsiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromMicrosiemens(double microsiemens) + { + double value = (double) microsiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); + } + /// + /// Get ElectricConductance from Millisiemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromMillisiemens(double millisiemens) + { + double value = (double) millisiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); + } + /// + /// Get ElectricConductance from Siemens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductance FromSiemens(double siemens) + { + double value = (double) siemens; + return new ElectricConductance(value, ElectricConductanceUnit.Siemens); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ElectricConductance unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) + { + return new ElectricConductance((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +279,343 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricConductance Parse(string str, [CanBeNull] string cultureName) + public static ElectricConductance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricConductanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemens(x.Siemens + y.Siemens)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricConductance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricConductanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricConductanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == ElectricConductanceUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricConductance to another ElectricConductance with the unit representation . + /// + /// A ElectricConductance with the specified unit. + public ElectricConductance ToUnit(ElectricConductanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricConductance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricConductanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs index 659eb4a048..843805c29e 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricConductivity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductivityUnit? _unit; + + static ElectricConductivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit SiemensPerMeter. /// @@ -75,28 +83,154 @@ public ElectricConductivity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricConductivity(double numericValue, ElectricConductivityUnit unit) + { + if(unit == ElectricConductivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. + /// + public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; + + /// + /// Represents the largest possible value of ElectricConductivity + /// + public static ElectricConductivity MaxValue => new ElectricConductivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricConductivity + /// + public static ElectricConductivity MinValue => new ElectricConductivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricConductivity; + + /// + /// All units of measurement for the ElectricConductivity quantity. + /// + public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. + /// + public static ElectricConductivity Zero => new ElectricConductivity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricConductivity in SiemensPerMeter. + /// + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductivity from SiemensPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) + { + double value = (double) siemenspermeter; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricConductivity Parse(string str, [CanBeNull] string cultureName) + public static ElectricConductivity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricConductivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemensPerMeter(x.SiemensPerMeter + y.SiemensPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricConductivity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricConductivityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductivityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricConductivityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricConductivityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs index 74dc0b4cfb..31c19ff2db 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCurrent + public sealed partial class ElectricCurrent : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentUnit? _unit; + static ElectricCurrent() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Ampere. /// @@ -75,28 +80,259 @@ public ElectricCurrent() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricCurrent(double numericValue, ElectricCurrentUnit unit) + { + if(unit == ElectricCurrentUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. + /// + public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; + + /// + /// Represents the largest possible value of ElectricCurrent + /// + public static ElectricCurrent MaxValue => new ElectricCurrent(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrent + /// + public static ElectricCurrent MinValue => new ElectricCurrent(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrent; + + /// + /// All units of measurement for the ElectricCurrent quantity. + /// + public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. + /// + public static ElectricCurrent Zero => new ElectricCurrent(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrent.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrent in Amperes. + /// + public double Amperes => As(ElectricCurrentUnit.Ampere); + + /// + /// Get ElectricCurrent in Centiamperes. + /// + public double Centiamperes => As(ElectricCurrentUnit.Centiampere); + + /// + /// Get ElectricCurrent in Kiloamperes. + /// + public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); + + /// + /// Get ElectricCurrent in Megaamperes. + /// + public double Megaamperes => As(ElectricCurrentUnit.Megaampere); + + /// + /// Get ElectricCurrent in Microamperes. + /// + public double Microamperes => As(ElectricCurrentUnit.Microampere); + + /// + /// Get ElectricCurrent in Milliamperes. + /// + public double Milliamperes => As(ElectricCurrentUnit.Milliampere); + + /// + /// Get ElectricCurrent in Nanoamperes. + /// + public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); + + /// + /// Get ElectricCurrent in Picoamperes. + /// + public double Picoamperes => As(ElectricCurrentUnit.Picoampere); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get ElectricCurrent from Amperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromAmperes(double amperes) + { + double value = (double) amperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); + } + /// + /// Get ElectricCurrent from Centiamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromCentiamperes(double centiamperes) + { + double value = (double) centiamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); + } + /// + /// Get ElectricCurrent from Kiloamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromKiloamperes(double kiloamperes) + { + double value = (double) kiloamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); + } + /// + /// Get ElectricCurrent from Megaamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMegaamperes(double megaamperes) + { + double value = (double) megaamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); + } + /// + /// Get ElectricCurrent from Microamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMicroamperes(double microamperes) + { + double value = (double) microamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); + } + /// + /// Get ElectricCurrent from Milliamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromMilliamperes(double milliamperes) + { + double value = (double) milliamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); + } + /// + /// Get ElectricCurrent from Nanoamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromNanoamperes(double nanoamperes) + { + double value = (double) nanoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); + } + /// + /// Get ElectricCurrent from Picoamperes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrent FromPicoamperes(double picoamperes) + { + double value = (double) picoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +351,353 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] strin /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrent Parse(string str, [CanBeNull] string cultureName) + public static ElectricCurrent Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperes(x.Amperes + y.Amperes)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricCurrent); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricCurrentUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricCurrentUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == ElectricCurrentUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricCurrentUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs index c0893a10d3..ba1566386b 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In electromagnetism, current density is the electric current per unit area of cross section. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricCurrentDensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentDensityUnit? _unit; + + static ElectricCurrentDensity() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit AmperePerSquareMeter. /// @@ -75,28 +83,154 @@ public ElectricCurrentDensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricCurrentDensity(double numericValue, ElectricCurrentDensityUnit unit) + { + if(unit == ElectricCurrentDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. + /// + public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; + + /// + /// Represents the largest possible value of ElectricCurrentDensity + /// + public static ElectricCurrentDensity MaxValue => new ElectricCurrentDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrentDensity + /// + public static ElectricCurrentDensity MinValue => new ElectricCurrentDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; + + /// + /// All units of measurement for the ElectricCurrentDensity quantity. + /// + public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// + public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentDensity in AmperesPerSquareMeter. + /// + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentDensity from AmperesPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) + { + double value = (double) amperespersquaremeter; + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrentDensity Parse(string str, [CanBeNull] string cultureName) + public static ElectricCurrentDensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerSquareMeter(x.AmperesPerSquareMeter + y.AmperesPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricCurrentDensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricCurrentDensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricCurrentDensityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs index 8f7055a8ff..79a90f05ca 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In electromagnetism, the current gradient describes how the current changes in time. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCurrentGradient + public sealed partial class ElectricCurrentGradient : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentGradientUnit? _unit; + + static ElectricCurrentGradient() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit AmperePerSecond. /// @@ -75,28 +80,154 @@ public ElectricCurrentGradient() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricCurrentGradient(double numericValue, ElectricCurrentGradientUnit unit) + { + if(unit == ElectricCurrentGradientUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. + /// + public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; + + /// + /// Represents the largest possible value of ElectricCurrentGradient + /// + public static ElectricCurrentGradient MaxValue => new ElectricCurrentGradient(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrentGradient + /// + public static ElectricCurrentGradient MinValue => new ElectricCurrentGradient(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; + + /// + /// All units of measurement for the ElectricCurrentGradient quantity. + /// + public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. + /// + public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentGradient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentGradient in AmperesPerSecond. + /// + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentGradientUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricCurrentGradient from AmperesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) + { + double value = (double) amperespersecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +246,339 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrentGradient Parse(string str, [CanBeNull] string cultureName) + public static ElectricCurrentGradient Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentGradientUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerSecond(x.AmperesPerSecond + y.AmperesPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricCurrentGradient); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricCurrentGradientUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentGradientUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricCurrentGradientUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentGradientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs index 0d3882d3fb..758928d9bf 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricField : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricFieldUnit? _unit; + + static ElectricField() + { + BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit VoltPerMeter. /// @@ -75,28 +83,154 @@ public ElectricField() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricField(double numericValue, ElectricFieldUnit unit) + { + if(unit == ElectricFieldUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. + /// + public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; + + /// + /// Represents the largest possible value of ElectricField + /// + public static ElectricField MaxValue => new ElectricField(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricField + /// + public static ElectricField MinValue => new ElectricField(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricField; + + /// + /// All units of measurement for the ElectricField quantity. + /// + public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. + /// + public static ElectricField Zero => new ElectricField(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricField in VoltsPerMeter. + /// + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricField from VoltsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricField FromVoltsPerMeter(double voltspermeter) + { + double value = (double) voltspermeter; + return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricField Parse(string str, [CanBeNull] string cultureName) + public static ElectricField Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricFieldUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsPerMeter(x.VoltsPerMeter + y.VoltsPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricField); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricFieldUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricFieldUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricFieldUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == ElectricFieldUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricFieldUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs index 306892156d..6fee355e37 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Inductance is a property of an electrical conductor which opposes a change in current. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricInductance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricInductanceUnit? _unit; + + static ElectricInductance() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Henry. /// @@ -75,28 +83,199 @@ public ElectricInductance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricInductance(double numericValue, ElectricInductanceUnit unit) + { + if(unit == ElectricInductanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. + /// + public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; + + /// + /// Represents the largest possible value of ElectricInductance + /// + public static ElectricInductance MaxValue => new ElectricInductance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricInductance + /// + public static ElectricInductance MinValue => new ElectricInductance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricInductance; + + /// + /// All units of measurement for the ElectricInductance quantity. + /// + public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Henry. + /// + public static ElectricInductance Zero => new ElectricInductance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricInductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricInductance in Henries. + /// + public double Henries => As(ElectricInductanceUnit.Henry); + + /// + /// Get ElectricInductance in Microhenries. + /// + public double Microhenries => As(ElectricInductanceUnit.Microhenry); + + /// + /// Get ElectricInductance in Millihenries. + /// + public double Millihenries => As(ElectricInductanceUnit.Millihenry); + + /// + /// Get ElectricInductance in Nanohenries. + /// + public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ElectricInductance from Henries. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricInductance FromHenries(double henries) + { + double value = (double) henries; + return new ElectricInductance(value, ElectricInductanceUnit.Henry); + } + /// + /// Get ElectricInductance from Microhenries. + /// + /// 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); + } + /// + /// Get ElectricInductance from Millihenries. + /// + /// 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); + } + /// + /// Get ElectricInductance from Nanohenries. + /// + /// 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); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +294,345 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] st /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricInductance Parse(string str, [CanBeNull] string cultureName) + public static ElectricInductance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricInductanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHenries(x.Henries + y.Henries)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricInductance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricInductanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricInductanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == ElectricInductanceUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricInductanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricInductance to another ElectricInductance with the unit representation . + /// + /// A ElectricInductance with the specified unit. + public ElectricInductance ToUnit(ElectricInductanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricInductance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricInductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricInductanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs index d2e374ae8d..546af6e12b 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotential + public sealed partial class ElectricPotential : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialUnit? _unit; + static ElectricPotential() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Volt. /// @@ -75,28 +80,214 @@ public ElectricPotential() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricPotential(double numericValue, ElectricPotentialUnit unit) + { + if(unit == ElectricPotentialUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. + /// + public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; + + /// + /// Represents the largest possible value of ElectricPotential + /// + public static ElectricPotential MaxValue => new ElectricPotential(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotential + /// + public static ElectricPotential MinValue => new ElectricPotential(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotential; + + /// + /// All units of measurement for the ElectricPotential quantity. + /// + public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Volt. + /// + public static ElectricPotential Zero => new ElectricPotential(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotential.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotential in Kilovolts. + /// + public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); + + /// + /// Get ElectricPotential in Megavolts. + /// + public double Megavolts => As(ElectricPotentialUnit.Megavolt); + + /// + /// Get ElectricPotential in Microvolts. + /// + public double Microvolts => As(ElectricPotentialUnit.Microvolt); + + /// + /// Get ElectricPotential in Millivolts. + /// + public double Millivolts => As(ElectricPotentialUnit.Millivolt); + + /// + /// Get ElectricPotential in Volts. + /// + public double Volts => As(ElectricPotentialUnit.Volt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotential from Kilovolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromKilovolts(double kilovolts) + { + double value = (double) kilovolts; + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); + } + /// + /// Get ElectricPotential from Megavolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMegavolts(double megavolts) + { + double value = (double) megavolts; + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); + } + /// + /// Get ElectricPotential from Microvolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMicrovolts(double microvolts) + { + double value = (double) microvolts; + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); + } + /// + /// Get ElectricPotential from Millivolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromMillivolts(double millivolts) + { + double value = (double) millivolts; + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); } + /// + /// Get ElectricPotential from Volts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotential FromVolts(double volts) + { + double value = (double) volts; + return new ElectricPotential(value, ElectricPotentialUnit.Volt); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ElectricPotential unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) + { + return new ElectricPotential((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +306,347 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] str /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotential Parse(string str, [CanBeNull] string cultureName) + public static ElectricPotential Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVolts(x.Volts + y.Volts)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricPotential); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricPotentialUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricPotentialUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is ElectricPotential objElectricPotential)) + return false; - if (unit == ElectricPotentialUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricPotential to another ElectricPotential with the unit representation . + /// + /// A ElectricPotential with the specified unit. + public ElectricPotential ToUnit(ElectricPotentialUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotential(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricPotentialUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs index 8db3b6ef8f..153a1e0aa2 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The Electric Potential of a system known to use Alternating Current. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotentialAc + public sealed partial class ElectricPotentialAc : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialAcUnit? _unit; + static ElectricPotentialAc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit VoltAc. /// @@ -75,28 +80,214 @@ public ElectricPotentialAc() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit) + { + if(unit == ElectricPotentialAcUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. + /// + public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; + + /// + /// Represents the largest possible value of ElectricPotentialAc + /// + public static ElectricPotentialAc MaxValue => new ElectricPotentialAc(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotentialAc + /// + public static ElectricPotentialAc MinValue => new ElectricPotentialAc(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotentialAc; + + /// + /// All units of measurement for the ElectricPotentialAc quantity. + /// + public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. + /// + public static ElectricPotentialAc Zero => new ElectricPotentialAc(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialAc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotentialAc in KilovoltsAc. + /// + public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); + + /// + /// Get ElectricPotentialAc in MegavoltsAc. + /// + public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); + + /// + /// Get ElectricPotentialAc in MicrovoltsAc. + /// + public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); + + /// + /// Get ElectricPotentialAc in MillivoltsAc. + /// + public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); + + /// + /// Get ElectricPotentialAc in VoltsAc. + /// + public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialAcUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialAc from KilovoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) + { + double value = (double) kilovoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); + } + /// + /// Get ElectricPotentialAc from MegavoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) + { + double value = (double) megavoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); + } + /// + /// Get ElectricPotentialAc from MicrovoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) + { + double value = (double) microvoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); + } + /// + /// Get ElectricPotentialAc from MillivoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) + { + double value = (double) millivoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); } + /// + /// Get ElectricPotentialAc from VoltsAc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialAc FromVoltsAc(double voltsac) + { + double value = (double) voltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ElectricPotentialAc unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fromUnit) + { + return new ElectricPotentialAc((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +306,347 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotentialAc Parse(string str, [CanBeNull] string cultureName) + public static ElectricPotentialAc Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialAcUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsAc(x.VoltsAc + y.VoltsAc)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricPotentialAc); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricPotentialAcUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is ElectricPotentialAc objElectricPotentialAc)) + return false; - if (unit == ElectricPotentialAcUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialAcUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . + /// + /// A ElectricPotentialAc with the specified unit. + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotentialAc(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialAcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs index 9446dfaee1..adf9532fd1 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The Electric Potential of a system known to use Direct Current. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotentialDc + public sealed partial class ElectricPotentialDc : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialDcUnit? _unit; + static ElectricPotentialDc() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit VoltDc. /// @@ -75,28 +80,214 @@ public ElectricPotentialDc() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricPotentialDc(double numericValue, ElectricPotentialDcUnit unit) + { + if(unit == ElectricPotentialDcUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. + /// + public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; + + /// + /// Represents the largest possible value of ElectricPotentialDc + /// + public static ElectricPotentialDc MaxValue => new ElectricPotentialDc(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotentialDc + /// + public static ElectricPotentialDc MinValue => new ElectricPotentialDc(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotentialDc; + + /// + /// All units of measurement for the ElectricPotentialDc quantity. + /// + public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. + /// + public static ElectricPotentialDc Zero => new ElectricPotentialDc(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialDc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotentialDc in KilovoltsDc. + /// + public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); + + /// + /// Get ElectricPotentialDc in MegavoltsDc. + /// + public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); + + /// + /// Get ElectricPotentialDc in MicrovoltsDc. + /// + public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); + + /// + /// Get ElectricPotentialDc in MillivoltsDc. + /// + public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); + + /// + /// Get ElectricPotentialDc in VoltsDc. + /// + public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialDcUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialDc from KilovoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) + { + double value = (double) kilovoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); + } + /// + /// Get ElectricPotentialDc from MegavoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) + { + double value = (double) megavoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); + } + /// + /// Get ElectricPotentialDc from MicrovoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) + { + double value = (double) microvoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); + } + /// + /// Get ElectricPotentialDc from MillivoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) + { + double value = (double) millivoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); } + /// + /// Get ElectricPotentialDc from VoltsDc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricPotentialDc FromVoltsDc(double voltsdc) + { + double value = (double) voltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ElectricPotentialDc unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fromUnit) + { + return new ElectricPotentialDc((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +306,347 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotentialDc Parse(string str, [CanBeNull] string cultureName) + public static ElectricPotentialDc Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialDcUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsDc(x.VoltsDc + y.VoltsDc)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricPotentialDc); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricPotentialDcUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is ElectricPotentialDc objElectricPotentialDc)) + return false; - if (unit == ElectricPotentialDcUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialDcUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . + /// + /// A ElectricPotentialDc with the specified unit. + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotentialDc(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialDcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs index fcc1d95375..3784856cea 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricResistance + public sealed partial class ElectricResistance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistanceUnit? _unit; + static ElectricResistance() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Ohm. /// @@ -75,28 +80,214 @@ public ElectricResistance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricResistance(double numericValue, ElectricResistanceUnit unit) + { + if(unit == ElectricResistanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. + /// + public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; + + /// + /// Represents the largest possible value of ElectricResistance + /// + public static ElectricResistance MaxValue => new ElectricResistance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricResistance + /// + public static ElectricResistance MinValue => new ElectricResistance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricResistance; + + /// + /// All units of measurement for the ElectricResistance quantity. + /// + public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. + /// + public static ElectricResistance Zero => new ElectricResistance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricResistance in Gigaohms. + /// + public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); + + /// + /// Get ElectricResistance in Kiloohms. + /// + public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); + + /// + /// Get ElectricResistance in Megaohms. + /// + public double Megaohms => As(ElectricResistanceUnit.Megaohm); + + /// + /// Get ElectricResistance in Milliohms. + /// + public double Milliohms => As(ElectricResistanceUnit.Milliohm); + + /// + /// Get ElectricResistance in Ohms. + /// + public double Ohms => As(ElectricResistanceUnit.Ohm); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistance from Gigaohms. + /// + /// 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); + } + /// + /// Get ElectricResistance from Kiloohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromKiloohms(double kiloohms) + { + double value = (double) kiloohms; + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); + } + /// + /// Get ElectricResistance from Megaohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromMegaohms(double megaohms) + { + double value = (double) megaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); + } + /// + /// Get ElectricResistance from Milliohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromMilliohms(double milliohms) + { + double value = (double) milliohms; + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); } + /// + /// Get ElectricResistance from Ohms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistance FromOhms(double ohms) + { + double value = (double) ohms; + return new ElectricResistance(value, ElectricResistanceUnit.Ohm); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ElectricResistance unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) + { + return new ElectricResistance((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +306,347 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] st /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricResistance Parse(string str, [CanBeNull] string cultureName) + public static ElectricResistance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricResistanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromOhms(x.Ohms + y.Ohms)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricResistance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricResistanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is ElectricResistance objElectricResistance)) + return false; - if (unit == ElectricResistanceUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricResistance to another ElectricResistance with the unit representation . + /// + /// A ElectricResistance with the specified unit. + public ElectricResistance ToUnit(ElectricResistanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricResistance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricResistanceUnit.Gigaohm: return (_value) * 1e9d; + case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; + case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; + case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; + case ElectricResistanceUnit.Ohm: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + 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.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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricResistanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs index e8259ace93..92d978ba66 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ElectricResistivity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistivityUnit? _unit; + + static ElectricResistivity() + { + BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit OhmMeter. /// @@ -75,28 +83,199 @@ public ElectricResistivity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ElectricResistivity(double numericValue, ElectricResistivityUnit unit) + { + if(unit == ElectricResistivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. + /// + public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; + + /// + /// Represents the largest possible value of ElectricResistivity + /// + public static ElectricResistivity MaxValue => new ElectricResistivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricResistivity + /// + public static ElectricResistivity MinValue => new ElectricResistivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricResistivity; + + /// + /// All units of measurement for the ElectricResistivity quantity. + /// + public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. + /// + public static ElectricResistivity Zero => new ElectricResistivity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricResistivity in MicroohmMeters. + /// + public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); + + /// + /// Get ElectricResistivity in MilliohmMeters. + /// + public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); + + /// + /// Get ElectricResistivity in NanoohmMeters. + /// + public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); + + /// + /// Get ElectricResistivity in OhmMeters. + /// + public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ElectricResistivity from MicroohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromMicroohmMeters(double microohmmeters) + { + double value = (double) microohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); + } + /// + /// Get ElectricResistivity from MilliohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) + { + double value = (double) milliohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); + } + /// + /// Get ElectricResistivity from NanoohmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) + { + double value = (double) nanoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); + } + /// + /// Get ElectricResistivity from OhmMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ElectricResistivity FromOhmMeters(double ohmmeters) + { + double value = (double) ohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +294,345 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricResistivity Parse(string str, [CanBeNull] string cultureName) + public static ElectricResistivity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricResistivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromOhmMeters(x.OhmMeters + y.OhmMeters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ElectricResistivity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ElectricResistivityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ElectricResistivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == ElectricResistivityUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . + /// + /// A ElectricResistivity with the specified unit. + public ElectricResistivity ToUnit(ElectricResistivityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ElectricResistivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; + case ElectricResistivityUnit.OhmMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(ElectricResistivityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; + case ElectricResistivityUnit.OhmMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ElectricResistivityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs index 8ecbcbd9b8..6003594404 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Energy + public sealed partial class Energy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly EnergyUnit? _unit; + + static Energy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Joule. /// @@ -75,28 +80,469 @@ public Energy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Energy(double numericValue, EnergyUnit unit) + { + if(unit == EnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Energy, which is Joule. All conversions go via this value. + /// + public static EnergyUnit BaseUnit => EnergyUnit.Joule; + + /// + /// Represents the largest possible value of Energy + /// + public static Energy MaxValue => new Energy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Energy + /// + public static Energy MinValue => new Energy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Energy; + + /// + /// All units of measurement for the Energy quantity. + /// + public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Joule. + /// + public static Energy Zero => new Energy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Energy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Energy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Energy in BritishThermalUnits. + /// + public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); + + /// + /// Get Energy in Calories. + /// + public double Calories => As(EnergyUnit.Calorie); + + /// + /// Get Energy in DecathermsEc. + /// + public double DecathermsEc => As(EnergyUnit.DecathermEc); + + /// + /// Get Energy in DecathermsImperial. + /// + public double DecathermsImperial => As(EnergyUnit.DecathermImperial); + + /// + /// Get Energy in DecathermsUs. + /// + public double DecathermsUs => As(EnergyUnit.DecathermUs); + + /// + /// Get Energy in ElectronVolts. + /// + public double ElectronVolts => As(EnergyUnit.ElectronVolt); + + /// + /// Get Energy in Ergs. + /// + public double Ergs => As(EnergyUnit.Erg); + + /// + /// Get Energy in FootPounds. + /// + public double FootPounds => As(EnergyUnit.FootPound); + + /// + /// Get Energy in GigabritishThermalUnits. + /// + public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); + + /// + /// Get Energy in GigawattHours. + /// + public double GigawattHours => As(EnergyUnit.GigawattHour); + + /// + /// Get Energy in Joules. + /// + public double Joules => As(EnergyUnit.Joule); + + /// + /// Get Energy in KilobritishThermalUnits. + /// + public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); + + /// + /// Get Energy in Kilocalories. + /// + public double Kilocalories => As(EnergyUnit.Kilocalorie); + + /// + /// Get Energy in Kilojoules. + /// + public double Kilojoules => As(EnergyUnit.Kilojoule); + + /// + /// Get Energy in KilowattHours. + /// + public double KilowattHours => As(EnergyUnit.KilowattHour); + + /// + /// Get Energy in MegabritishThermalUnits. + /// + public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); + + /// + /// Get Energy in Megajoules. + /// + public double Megajoules => As(EnergyUnit.Megajoule); + + /// + /// Get Energy in MegawattHours. + /// + public double MegawattHours => As(EnergyUnit.MegawattHour); + + /// + /// Get Energy in ThermsEc. + /// + public double ThermsEc => As(EnergyUnit.ThermEc); + + /// + /// Get Energy in ThermsImperial. + /// + public double ThermsImperial => As(EnergyUnit.ThermImperial); + + /// + /// Get Energy in ThermsUs. + /// + public double ThermsUs => As(EnergyUnit.ThermUs); + + /// + /// Get Energy in WattHours. + /// + public double WattHours => As(EnergyUnit.WattHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Energy from BritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromBritishThermalUnits(double britishthermalunits) + { + double value = (double) britishthermalunits; + return new Energy(value, EnergyUnit.BritishThermalUnit); + } + /// + /// Get Energy from Calories. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromCalories(double calories) + { + double value = (double) calories; + return new Energy(value, EnergyUnit.Calorie); + } + /// + /// Get Energy from DecathermsEc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsEc(double decathermsec) + { + double value = (double) decathermsec; + return new Energy(value, EnergyUnit.DecathermEc); } + /// + /// Get Energy from DecathermsImperial. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsImperial(double decathermsimperial) + { + double value = (double) decathermsimperial; + return new Energy(value, EnergyUnit.DecathermImperial); + } + /// + /// Get Energy from DecathermsUs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromDecathermsUs(double decathermsus) + { + double value = (double) decathermsus; + return new Energy(value, EnergyUnit.DecathermUs); + } + /// + /// Get Energy from ElectronVolts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromElectronVolts(double electronvolts) + { + double value = (double) electronvolts; + return new Energy(value, EnergyUnit.ElectronVolt); + } + /// + /// Get Energy from Ergs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromErgs(double ergs) + { + double value = (double) ergs; + return new Energy(value, EnergyUnit.Erg); + } + /// + /// Get Energy from FootPounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromFootPounds(double footpounds) + { + double value = (double) footpounds; + return new Energy(value, EnergyUnit.FootPound); + } + /// + /// Get Energy from GigabritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) + { + double value = (double) gigabritishthermalunits; + return new Energy(value, EnergyUnit.GigabritishThermalUnit); + } + /// + /// Get Energy from GigawattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromGigawattHours(double gigawatthours) + { + double value = (double) gigawatthours; + return new Energy(value, EnergyUnit.GigawattHour); + } + /// + /// Get Energy from Joules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromJoules(double joules) + { + double value = (double) joules; + return new Energy(value, EnergyUnit.Joule); + } + /// + /// Get Energy from KilobritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) + { + double value = (double) kilobritishthermalunits; + return new Energy(value, EnergyUnit.KilobritishThermalUnit); + } + /// + /// Get Energy from Kilocalories. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilocalories(double kilocalories) + { + double value = (double) kilocalories; + return new Energy(value, EnergyUnit.Kilocalorie); + } + /// + /// Get Energy from Kilojoules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilojoules(double kilojoules) + { + double value = (double) kilojoules; + return new Energy(value, EnergyUnit.Kilojoule); + } + /// + /// Get Energy from KilowattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromKilowattHours(double kilowatthours) + { + double value = (double) kilowatthours; + return new Energy(value, EnergyUnit.KilowattHour); + } + /// + /// Get Energy from MegabritishThermalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) + { + double value = (double) megabritishthermalunits; + return new Energy(value, EnergyUnit.MegabritishThermalUnit); + } + /// + /// Get Energy from Megajoules. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegajoules(double megajoules) + { + double value = (double) megajoules; + return new Energy(value, EnergyUnit.Megajoule); + } + /// + /// Get Energy from MegawattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromMegawattHours(double megawatthours) + { + double value = (double) megawatthours; + return new Energy(value, EnergyUnit.MegawattHour); + } + /// + /// Get Energy from ThermsEc. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsEc(double thermsec) + { + double value = (double) thermsec; + return new Energy(value, EnergyUnit.ThermEc); + } + /// + /// Get Energy from ThermsImperial. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsImperial(double thermsimperial) + { + double value = (double) thermsimperial; + return new Energy(value, EnergyUnit.ThermImperial); + } + /// + /// Get Energy from ThermsUs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromThermsUs(double thermsus) + { + double value = (double) thermsus; + return new Energy(value, EnergyUnit.ThermUs); + } + /// + /// Get Energy from WattHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Energy FromWattHours(double watthours) + { + double value = (double) watthours; + return new Energy(value, EnergyUnit.WattHour); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Energy unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Energy From(double value, EnergyUnit fromUnit) + { + return new Energy((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +561,381 @@ public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] string culture /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Energy Parse(string str, [CanBeNull] string cultureName) + public static Energy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - EnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoules(x.Joules + y.Joules)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Energy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static EnergyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static EnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #region Conversion Methods - if (unit == EnergyUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; + case EnergyUnit.Calorie: return _value*4.184; + case EnergyUnit.DecathermEc: return (_value*1.05505585262e8) * 1e1d; + case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e8) * 1e1d; + case EnergyUnit.DecathermUs: return (_value*1.054804e8) * 1e1d; + case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; + case EnergyUnit.Erg: return _value*1e-7; + case EnergyUnit.FootPound: return _value*1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; + case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; + case EnergyUnit.Joule: return _value; + case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; + case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; + case EnergyUnit.Kilojoule: return (_value) * 1e3d; + case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; + case EnergyUnit.Megajoule: return (_value) * 1e6d; + case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; + case EnergyUnit.ThermEc: return _value*1.05505585262e8; + case EnergyUnit.ThermImperial: return _value*1.05505585257348e8; + case EnergyUnit.ThermUs: return _value*1.054804e8; + case EnergyUnit.WattHour: return _value*3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(EnergyUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; + case EnergyUnit.Calorie: return baseUnitValue/4.184; + case EnergyUnit.DecathermEc: return (baseUnitValue/1.05505585262e8) / 1e1d; + case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e8) / 1e1d; + case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e8) / 1e1d; + case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; + case EnergyUnit.Erg: return baseUnitValue/1e-7; + case EnergyUnit.FootPound: return baseUnitValue/1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; + case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; + case EnergyUnit.Joule: return baseUnitValue; + case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; + case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; + case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; + case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; + case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; + case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; + case EnergyUnit.ThermEc: return baseUnitValue/1.05505585262e8; + case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e8; + case EnergyUnit.ThermUs: return baseUnitValue/1.054804e8; + case EnergyUnit.WattHour: return baseUnitValue/3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(EnergyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs index 9388a4a857..3bb85a46fd 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Entropy + public sealed partial class Entropy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EntropyUnit? _unit; + static Entropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerKelvin. /// @@ -75,28 +80,244 @@ public Entropy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Entropy(double numericValue, EntropyUnit unit) + { + if(unit == EntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. + /// + public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; + + /// + /// Represents the largest possible value of Entropy + /// + public static Entropy MaxValue => new Entropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Entropy + /// + public static Entropy MinValue => new Entropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Entropy; + + /// + /// All units of measurement for the Entropy quantity. + /// + public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. + /// + public static Entropy Zero => new Entropy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Entropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Entropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Entropy in CaloriesPerKelvin. + /// + public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); + + /// + /// Get Entropy in JoulesPerDegreeCelsius. + /// + public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); + + /// + /// Get Entropy in JoulesPerKelvin. + /// + public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); + + /// + /// Get Entropy in KilocaloriesPerKelvin. + /// + public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); + + /// + /// Get Entropy in KilojoulesPerDegreeCelsius. + /// + public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); + + /// + /// Get Entropy in KilojoulesPerKelvin. + /// + public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); + + /// + /// Get Entropy in MegajoulesPerKelvin. + /// + public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Entropy from CaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) + { + double value = (double) caloriesperkelvin; + return new Entropy(value, EntropyUnit.CaloriePerKelvin); + } + /// + /// Get Entropy from JoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) + { + double value = (double) joulesperdegreecelsius; + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); + } + /// + /// Get Entropy from JoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromJoulesPerKelvin(double joulesperkelvin) + { + double value = (double) joulesperkelvin; + return new Entropy(value, EntropyUnit.JoulePerKelvin); + } + /// + /// Get Entropy from KilocaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) + { + double value = (double) kilocaloriesperkelvin; + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); + } + /// + /// Get Entropy from KilojoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) + { + double value = (double) kilojoulesperdegreecelsius; + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); + } + /// + /// Get Entropy from KilojoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) + { + double value = (double) kilojoulesperkelvin; + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); + } + /// + /// Get Entropy from MegajoulesPerKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) + { + double value = (double) megajoulesperkelvin; + return new Entropy(value, EntropyUnit.MegajoulePerKelvin); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +336,351 @@ public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] string cultur /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Entropy Parse(string str, [CanBeNull] string cultureName) + public static Entropy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - EntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKelvin(x.JoulesPerKelvin + y.JoulesPerKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Entropy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static EntropyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static EntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// Parse a unit string. + /// + /// String to 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 - if (unit == EntropyUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Entropy to another Entropy with the unit representation . + /// + /// A Entropy with the specified unit. + public Entropy ToUnit(EntropyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Entropy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(EntropyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + 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/Flow.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Flow.WindowsRuntimeComponent.g.cs deleted file mode 100644 index 401f367c0c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Flow.WindowsRuntimeComponent.g.cs +++ /dev/null @@ -1,254 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Flow - { - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Flow() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FlowUnit unit, [CanBeNull] string cultureName) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); - } - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Flow Parse(string str, [CanBeNull] string cultureName) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - FlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerSecond(x.CubicMetersPerSecond + y.CubicMetersPerSecond)); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Flow result) - { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Flow); - return false; - } - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FlowUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - internal static FlowUnit ParseUnit(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); - - if (unit == FlowUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - #endregion - - #region ToString Methods - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// String representation. - public string ToString(FlowUnit unit, [CanBeNull] string cultureName) - { - return ToString(unit, cultureName, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) - { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); - } - - /// - /// Get string representation of value and unit. - /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs index cfcd6b7e06..f681bc23b8 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Force + public sealed partial class Force : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceUnit? _unit; + + static Force() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Newton. /// @@ -75,28 +80,334 @@ public Force() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Force(double numericValue, ForceUnit unit) + { + if(unit == ForceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Force, which is Newton. All conversions go via this value. + /// + public static ForceUnit BaseUnit => ForceUnit.Newton; + + /// + /// Represents the largest possible value of Force + /// + public static Force MaxValue => new Force(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Force + /// + public static Force MinValue => new Force(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Force; + + /// + /// All units of measurement for the Force quantity. + /// + public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Newton. + /// + public static Force Zero => new Force(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Force.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Force.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Force in Decanewtons. + /// + public double Decanewtons => As(ForceUnit.Decanewton); + + /// + /// Get Force in Dyne. + /// + public double Dyne => As(ForceUnit.Dyn); + + /// + /// Get Force in KilogramsForce. + /// + public double KilogramsForce => As(ForceUnit.KilogramForce); + + /// + /// Get Force in Kilonewtons. + /// + public double Kilonewtons => As(ForceUnit.Kilonewton); + + /// + /// Get Force in KiloPonds. + /// + public double KiloPonds => As(ForceUnit.KiloPond); + + /// + /// Get Force in Meganewtons. + /// + public double Meganewtons => As(ForceUnit.Meganewton); + + /// + /// Get Force in Micronewtons. + /// + public double Micronewtons => As(ForceUnit.Micronewton); + + /// + /// Get Force in Millinewtons. + /// + public double Millinewtons => As(ForceUnit.Millinewton); + + /// + /// Get Force in Newtons. + /// + public double Newtons => As(ForceUnit.Newton); + + /// + /// Get Force in OunceForce. + /// + public double OunceForce => As(ForceUnit.OunceForce); + + /// + /// Get Force in Poundals. + /// + public double Poundals => As(ForceUnit.Poundal); + + /// + /// Get Force in PoundsForce. + /// + public double PoundsForce => As(ForceUnit.PoundForce); + + /// + /// Get Force in TonnesForce. + /// + public double TonnesForce => As(ForceUnit.TonneForce); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ForceUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Force from Decanewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromDecanewtons(double decanewtons) + { + double value = (double) decanewtons; + return new Force(value, ForceUnit.Decanewton); + } + /// + /// Get Force from Dyne. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromDyne(double dyne) + { + double value = (double) dyne; + return new Force(value, ForceUnit.Dyn); + } + /// + /// Get Force from KilogramsForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKilogramsForce(double kilogramsforce) + { + double value = (double) kilogramsforce; + return new Force(value, ForceUnit.KilogramForce); + } + /// + /// Get Force from Kilonewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKilonewtons(double kilonewtons) + { + double value = (double) kilonewtons; + return new Force(value, ForceUnit.Kilonewton); + } + /// + /// Get Force from KiloPonds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromKiloPonds(double kiloponds) + { + double value = (double) kiloponds; + return new Force(value, ForceUnit.KiloPond); + } + /// + /// Get Force from Meganewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMeganewtons(double meganewtons) + { + double value = (double) meganewtons; + return new Force(value, ForceUnit.Meganewton); + } + /// + /// Get Force from Micronewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMicronewtons(double micronewtons) + { + double value = (double) micronewtons; + return new Force(value, ForceUnit.Micronewton); + } + /// + /// Get Force from Millinewtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromMillinewtons(double millinewtons) + { + double value = (double) millinewtons; + return new Force(value, ForceUnit.Millinewton); + } + /// + /// Get Force from Newtons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromNewtons(double newtons) + { + double value = (double) newtons; + return new Force(value, ForceUnit.Newton); + } + /// + /// Get Force from OunceForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromOunceForce(double ounceforce) + { + double value = (double) ounceforce; + return new Force(value, ForceUnit.OunceForce); + } + /// + /// Get Force from Poundals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromPoundals(double poundals) + { + double value = (double) poundals; + return new Force(value, ForceUnit.Poundal); + } + /// + /// Get Force from PoundsForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromPoundsForce(double poundsforce) + { + double value = (double) poundsforce; + return new Force(value, ForceUnit.PoundForce); + } + /// + /// Get Force from TonnesForce. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Force FromTonnesForce(double tonnesforce) + { + double value = (double) tonnesforce; + return new Force(value, ForceUnit.TonneForce); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +426,363 @@ public static string GetAbbreviation(ForceUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Force Parse(string str, [CanBeNull] string cultureName) + public static Force Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtons(x.Newtons + y.Newtons)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Force); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ForceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ForceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to 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."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == ForceUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Force. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Force to another Force with the unit representation . + /// + /// A Force with the specified unit. + public Force ToUnit(ForceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Force(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForceUnit.Decanewton: return (_value) * 1e1d; + case ForceUnit.Dyn: return _value/1e5; + case ForceUnit.KilogramForce: return _value*9.80665002864; + case ForceUnit.Kilonewton: return (_value) * 1e3d; + case ForceUnit.KiloPond: return _value*9.80665002864; + case ForceUnit.Meganewton: return (_value) * 1e6d; + case ForceUnit.Micronewton: return (_value) * 1e-6d; + case ForceUnit.Millinewton: return (_value) * 1e-3d; + case ForceUnit.Newton: return _value; + case ForceUnit.OunceForce: return _value*2.780138509537812e-1; + case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return _value*9.80665002864e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(ForceUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; + case ForceUnit.Dyn: return baseUnitValue*1e5; + case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; + case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; + case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; + case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; + case ForceUnit.Micronewton: return (baseUnitValue) / 1e-6d; + case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; + case ForceUnit.Newton: return baseUnitValue; + case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; + case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return baseUnitValue/9.80665002864e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ForceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs index f7eae0b524..130bbaaab2 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ForceChangeRate + public sealed partial class ForceChangeRate : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceChangeRateUnit? _unit; + + static ForceChangeRate() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonPerSecond. /// @@ -75,28 +80,304 @@ public ForceChangeRate() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ForceChangeRate(double numericValue, ForceChangeRateUnit unit) + { + if(unit == ForceChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. + /// + public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; + + /// + /// Represents the largest possible value of ForceChangeRate + /// + public static ForceChangeRate MaxValue => new ForceChangeRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ForceChangeRate + /// + public static ForceChangeRate MinValue => new ForceChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ForceChangeRate; + + /// + /// All units of measurement for the ForceChangeRate quantity. + /// + public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. + /// + public static ForceChangeRate Zero => new ForceChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForceChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ForceChangeRate in CentinewtonsPerSecond. + /// + public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); + + /// + /// Get ForceChangeRate in DecanewtonsPerMinute. + /// + public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); + + /// + /// Get ForceChangeRate in DecanewtonsPerSecond. + /// + public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); + + /// + /// Get ForceChangeRate in DecinewtonsPerSecond. + /// + public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); + + /// + /// Get ForceChangeRate in KilonewtonsPerMinute. + /// + public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); + + /// + /// Get ForceChangeRate in KilonewtonsPerSecond. + /// + public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); + + /// + /// Get ForceChangeRate in MicronewtonsPerSecond. + /// + public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); + + /// + /// Get ForceChangeRate in MillinewtonsPerSecond. + /// + public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); + + /// + /// Get ForceChangeRate in NanonewtonsPerSecond. + /// + public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); + + /// + /// Get ForceChangeRate in NewtonsPerMinute. + /// + public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); + + /// + /// Get ForceChangeRate in NewtonsPerSecond. + /// + public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForceChangeRate from CentinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) + { + double value = (double) centinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecanewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) + { + double value = (double) decanewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); + } + /// + /// Get ForceChangeRate from DecanewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) + { + double value = (double) decanewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); + } + /// + /// Get ForceChangeRate from DecinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) + { + double value = (double) decinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); + } + /// + /// Get ForceChangeRate from KilonewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) + { + double value = (double) kilonewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); + } + /// + /// Get ForceChangeRate from KilonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) + { + double value = (double) kilonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); + } + /// + /// Get ForceChangeRate from MicronewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) + { + double value = (double) micronewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); + } + /// + /// Get ForceChangeRate from MillinewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) + { + double value = (double) millinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); + } + /// + /// Get ForceChangeRate from NanonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) + { + double value = (double) nanonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); + } + /// + /// Get ForceChangeRate from NewtonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) + { + double value = (double) newtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); + } + /// + /// Get ForceChangeRate from NewtonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) + { + double value = (double) newtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +396,359 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] strin /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ForceChangeRate Parse(string str, [CanBeNull] string cultureName) + public static ForceChangeRate Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForceChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerSecond(x.NewtonsPerSecond + y.NewtonsPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ForceChangeRate); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ForceChangeRateUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ForceChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == ForceChangeRateUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . + /// + /// A ForceChangeRate with the specified unit. + public ForceChangeRate ToUnit(ForceChangeRateUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ForceChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return _value/60; + case ForceChangeRateUnit.NewtonPerSecond: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(ForceChangeRateUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; + case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ForceChangeRateUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs index 08af39e126..0d349719e1 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The magnitude of force per unit length. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ForcePerLength + public sealed partial class ForcePerLength : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForcePerLengthUnit? _unit; + static ForcePerLength() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonPerMeter. /// @@ -75,28 +80,274 @@ public ForcePerLength() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ForcePerLength(double numericValue, ForcePerLengthUnit unit) + { + if(unit == ForcePerLengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. + /// + public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; + + /// + /// Represents the largest possible value of ForcePerLength + /// + public static ForcePerLength MaxValue => new ForcePerLength(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ForcePerLength + /// + public static ForcePerLength MinValue => new ForcePerLength(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ForcePerLength; + + /// + /// All units of measurement for the ForcePerLength quantity. + /// + public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. + /// + public static ForcePerLength Zero => new ForcePerLength(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForcePerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ForcePerLength in CentinewtonsPerMeter. + /// + public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); + + /// + /// Get ForcePerLength in DecinewtonsPerMeter. + /// + public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); + + /// + /// Get ForcePerLength in KilogramsForcePerMeter. + /// + public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); + + /// + /// Get ForcePerLength in KilonewtonsPerMeter. + /// + public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); + + /// + /// Get ForcePerLength in MeganewtonsPerMeter. + /// + public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); + + /// + /// Get ForcePerLength in MicronewtonsPerMeter. + /// + public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); + + /// + /// Get ForcePerLength in MillinewtonsPerMeter. + /// + public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); + + /// + /// Get ForcePerLength in NanonewtonsPerMeter. + /// + public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); + + /// + /// Get ForcePerLength in NewtonsPerMeter. + /// + public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForcePerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ForcePerLength from CentinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) + { + double value = (double) centinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); + } + /// + /// Get ForcePerLength from DecinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) + { + double value = (double) decinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); + } + /// + /// Get ForcePerLength from KilogramsForcePerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) + { + double value = (double) kilogramsforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); + } + /// + /// Get ForcePerLength from KilonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) + { + double value = (double) kilonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); + } + /// + /// Get ForcePerLength from MeganewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) + { + double value = (double) meganewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); + } + /// + /// Get ForcePerLength from MicronewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) + { + double value = (double) micronewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); + } + /// + /// Get ForcePerLength from MillinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) + { + double value = (double) millinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); + } + /// + /// Get ForcePerLength from NanonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) + { + double value = (double) nanonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); + } + /// + /// Get ForcePerLength from NewtonsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) + { + double value = (double) newtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +366,355 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ForcePerLength Parse(string str, [CanBeNull] string cultureName) + public static ForcePerLength Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForcePerLengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerMeter(x.NewtonsPerMeter + y.NewtonsPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ForcePerLength); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ForcePerLengthUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ForcePerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForcePerLengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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); + } - if (unit == ForcePerLengthUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForcePerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(ForcePerLengthUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ForcePerLengthUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs index faa4ffba54..91e1b46e3d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The number of occurrences of a repeating event per unit time. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Frequency + public sealed partial class Frequency : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FrequencyUnit? _unit; + static Frequency() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Hertz. /// @@ -75,28 +80,259 @@ public Frequency() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Frequency(double numericValue, FrequencyUnit unit) + { + if(unit == FrequencyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Frequency, which is Hertz. All conversions go via this value. + /// + public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; + + /// + /// Represents the largest possible value of Frequency + /// + public static Frequency MaxValue => new Frequency(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Frequency + /// + public static Frequency MinValue => new Frequency(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Frequency; + + /// + /// All units of measurement for the Frequency quantity. + /// + public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. + /// + public static Frequency Zero => new Frequency(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Frequency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Frequency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Frequency in CyclesPerHour. + /// + public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); + + /// + /// Get Frequency in CyclesPerMinute. + /// + public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); + + /// + /// Get Frequency in Gigahertz. + /// + public double Gigahertz => As(FrequencyUnit.Gigahertz); + + /// + /// Get Frequency in Hertz. + /// + public double Hertz => As(FrequencyUnit.Hertz); + + /// + /// Get Frequency in Kilohertz. + /// + public double Kilohertz => As(FrequencyUnit.Kilohertz); + + /// + /// Get Frequency in Megahertz. + /// + public double Megahertz => As(FrequencyUnit.Megahertz); + + /// + /// Get Frequency in RadiansPerSecond. + /// + public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); + + /// + /// Get Frequency in Terahertz. + /// + public double Terahertz => As(FrequencyUnit.Terahertz); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Frequency from CyclesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromCyclesPerHour(double cyclesperhour) + { + double value = (double) cyclesperhour; + return new Frequency(value, FrequencyUnit.CyclePerHour); + } + /// + /// Get Frequency from CyclesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromCyclesPerMinute(double cyclesperminute) + { + double value = (double) cyclesperminute; + return new Frequency(value, FrequencyUnit.CyclePerMinute); + } + /// + /// Get Frequency from Gigahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromGigahertz(double gigahertz) + { + double value = (double) gigahertz; + return new Frequency(value, FrequencyUnit.Gigahertz); + } + /// + /// Get Frequency from Hertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromHertz(double hertz) + { + double value = (double) hertz; + return new Frequency(value, FrequencyUnit.Hertz); + } + /// + /// Get Frequency from Kilohertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromKilohertz(double kilohertz) + { + double value = (double) kilohertz; + return new Frequency(value, FrequencyUnit.Kilohertz); + } + /// + /// Get Frequency from Megahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromMegahertz(double megahertz) + { + double value = (double) megahertz; + return new Frequency(value, FrequencyUnit.Megahertz); + } + /// + /// Get Frequency from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromRadiansPerSecond(double radianspersecond) + { + double value = (double) radianspersecond; + return new Frequency(value, FrequencyUnit.RadianPerSecond); + } + /// + /// Get Frequency from Terahertz. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Frequency FromTerahertz(double terahertz) + { + double value = (double) terahertz; + return new Frequency(value, FrequencyUnit.Terahertz); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +351,353 @@ public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] string cult /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Frequency Parse(string str, [CanBeNull] string cultureName) + public static Frequency Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - FrequencyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHertz(x.Hertz + y.Hertz)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Frequency); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static FrequencyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static FrequencyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FrequencyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == FrequencyUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FrequencyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case FrequencyUnit.CyclePerHour: return _value/3600; + case FrequencyUnit.CyclePerMinute: return _value/60; + case FrequencyUnit.Gigahertz: return (_value) * 1e9d; + case FrequencyUnit.Hertz: return _value; + case FrequencyUnit.Kilohertz: return (_value) * 1e3d; + case FrequencyUnit.Megahertz: return (_value) * 1e6d; + case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; + case FrequencyUnit.Terahertz: return (_value) * 1e12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(FrequencyUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; + case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; + case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; + case FrequencyUnit.Hertz: return baseUnitValue; + case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; + case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; + case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; + case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(FrequencyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs index e48abae075..b7451ac273 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Heat flux is the flow of energy per unit of area per unit of time /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class HeatFlux + public sealed partial class HeatFlux : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatFluxUnit? _unit; + static HeatFlux() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. /// @@ -75,28 +80,409 @@ public HeatFlux() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private HeatFlux(double numericValue, HeatFluxUnit unit) + { + if(unit == HeatFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. + /// + public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; + + /// + /// Represents the largest possible value of HeatFlux + /// + public static HeatFlux MaxValue => new HeatFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of HeatFlux + /// + public static HeatFlux MinValue => new HeatFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.HeatFlux; + + /// + /// All units of measurement for the HeatFlux quantity. + /// + public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static HeatFlux Zero => new HeatFlux(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get HeatFlux in BtusPerHourSquareFoot. + /// + public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); + + /// + /// Get HeatFlux in BtusPerMinuteSquareFoot. + /// + public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); + + /// + /// Get HeatFlux in BtusPerSecondSquareFoot. + /// + public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); + + /// + /// Get HeatFlux in BtusPerSecondSquareInch. + /// + public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); + + /// + /// Get HeatFlux in CaloriesPerSecondSquareCentimeter. + /// + public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); + + /// + /// Get HeatFlux in CentiwattsPerSquareMeter. + /// + public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); + + /// + /// Get HeatFlux in DeciwattsPerSquareMeter. + /// + public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); + + /// + /// Get HeatFlux in KilocaloriesPerHourSquareMeter. + /// + public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); + + /// + /// Get HeatFlux in KilocaloriesPerSecondSquareCentimeter. + /// + public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + + /// + /// Get HeatFlux in KilowattsPerSquareMeter. + /// + public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); + + /// + /// Get HeatFlux in MicrowattsPerSquareMeter. + /// + public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); + + /// + /// Get HeatFlux in MilliwattsPerSquareMeter. + /// + public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); + + /// + /// Get HeatFlux in NanowattsPerSquareMeter. + /// + public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); + + /// + /// Get HeatFlux in PoundsForcePerFootSecond. + /// + public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); + + /// + /// Get HeatFlux in PoundsPerSecondCubed. + /// + public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); + + /// + /// Get HeatFlux in WattsPerSquareFoot. + /// + public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); + + /// + /// Get HeatFlux in WattsPerSquareInch. + /// + public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); + + /// + /// Get HeatFlux in WattsPerSquareMeter. + /// + public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get HeatFlux from BtusPerHourSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerHourSquareFoot(double btusperhoursquarefoot) + { + double value = (double) btusperhoursquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); + } + /// + /// Get HeatFlux from BtusPerMinuteSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerMinuteSquareFoot(double btusperminutesquarefoot) + { + double value = (double) btusperminutesquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerSecondSquareFoot(double btuspersecondsquarefoot) + { + double value = (double) btuspersecondsquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); + } + /// + /// Get HeatFlux from BtusPerSecondSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromBtusPerSecondSquareInch(double btuspersecondsquareinch) + { + double value = (double) btuspersecondsquareinch; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); + } + /// + /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double caloriespersecondsquarecentimeter) + { + double value = (double) caloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from CentiwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromCentiwattsPerSquareMeter(double centiwattspersquaremeter) + { + double value = (double) centiwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); + } + /// + /// Get HeatFlux from DeciwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromDeciwattsPerSquareMeter(double deciwattspersquaremeter) + { + double value = (double) deciwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerHourSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilocaloriesPerHourSquareMeter(double kilocaloriesperhoursquaremeter) + { + double value = (double) kilocaloriesperhoursquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); + } + /// + /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double kilocaloriespersecondsquarecentimeter) + { + double value = (double) kilocaloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + } + /// + /// Get HeatFlux from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromKilowattsPerSquareMeter(double kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); + } + /// + /// Get HeatFlux from MicrowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromMicrowattsPerSquareMeter(double microwattspersquaremeter) + { + double value = (double) microwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); + } + /// + /// Get HeatFlux from MilliwattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) + { + double value = (double) milliwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); + } + /// + /// Get HeatFlux from NanowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromNanowattsPerSquareMeter(double nanowattspersquaremeter) + { + double value = (double) nanowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); + } + /// + /// Get HeatFlux from PoundsForcePerFootSecond. + /// + /// 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); + } + /// + /// Get HeatFlux from PoundsPerSecondCubed. + /// + /// 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); + } + /// + /// Get HeatFlux from WattsPerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareFoot(double wattspersquarefoot) + { + double value = (double) wattspersquarefoot; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); + } + /// + /// Get HeatFlux from WattsPerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareInch(double wattspersquareinch) + { + double value = (double) wattspersquareinch; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); + } + /// + /// Get HeatFlux from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatFlux FromWattsPerSquareMeter(double wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// HeatFlux unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static HeatFlux From(double value, HeatFluxUnit fromUnit) + { + return new HeatFlux((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +501,373 @@ public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static HeatFlux Parse(string str, [CanBeNull] string cultureName) + public static HeatFlux Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - HeatFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeter(x.WattsPerSquareMeter + y.WattsPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(HeatFlux); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static HeatFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static HeatFluxUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static HeatFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == HeatFluxUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current HeatFlux. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this HeatFlux to another HeatFlux with the unit representation . + /// + /// A HeatFlux with the specified unit. + public HeatFlux ToUnit(HeatFluxUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new HeatFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(HeatFluxUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(HeatFluxUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(HeatFluxUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs index 68cce5ecda..40413dc114 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class HeatTransferCoefficient + public sealed partial class HeatTransferCoefficient : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatTransferCoefficientUnit? _unit; + + static HeatTransferCoefficient() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. /// @@ -75,28 +80,169 @@ public HeatTransferCoefficient() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private HeatTransferCoefficient(double numericValue, HeatTransferCoefficientUnit unit) + { + if(unit == HeatTransferCoefficientUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. + /// + public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + + /// + /// Represents the largest possible value of HeatTransferCoefficient + /// + public static HeatTransferCoefficient MaxValue => new HeatTransferCoefficient(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of HeatTransferCoefficient + /// + public static HeatTransferCoefficient MinValue => new HeatTransferCoefficient(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; + + /// + /// All units of measurement for the HeatTransferCoefficient quantity. + /// + public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// + public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatTransferCoefficient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. + /// + public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. + /// + public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatTransferCoefficientUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double wattspersquaremetercelsius) + { + double value = (double) wattspersquaremetercelsius; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + } + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double wattspersquaremeterkelvin) + { + double value = (double) wattspersquaremeterkelvin; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static HeatTransferCoefficient Parse(string str, [CanBeNull] string cultureName) + public static HeatTransferCoefficient Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - HeatTransferCoefficientUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeterKelvin(x.WattsPerSquareMeterKelvin + y.WattsPerSquareMeterKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(HeatTransferCoefficient); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static HeatTransferCoefficientUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static HeatTransferCoefficientUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == HeatTransferCoefficientUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatTransferCoefficientUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . + /// + /// A HeatTransferCoefficient with the specified unit. + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new HeatTransferCoefficient(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatTransferCoefficientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; + case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs index 6e9cdd4b6c..a5f6ee518a 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Illuminance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly IlluminanceUnit? _unit; + + static Illuminance() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + } /// /// Creates the quantity with a value of 0 in the base unit Lux. /// @@ -75,28 +83,199 @@ public Illuminance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Illuminance(double numericValue, IlluminanceUnit unit) + { + if(unit == IlluminanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Illuminance, which is Lux. All conversions go via this value. + /// + public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; + + /// + /// Represents the largest possible value of Illuminance + /// + public static Illuminance MaxValue => new Illuminance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Illuminance + /// + public static Illuminance MinValue => new Illuminance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Illuminance; + + /// + /// All units of measurement for the Illuminance quantity. + /// + public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lux. + /// + public static Illuminance Zero => new Illuminance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Illuminance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Illuminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Illuminance in Kilolux. + /// + public double Kilolux => As(IlluminanceUnit.Kilolux); + + /// + /// Get Illuminance in Lux. + /// + public double Lux => As(IlluminanceUnit.Lux); + + /// + /// Get Illuminance in Megalux. + /// + public double Megalux => As(IlluminanceUnit.Megalux); + + /// + /// Get Illuminance in Millilux. + /// + public double Millilux => As(IlluminanceUnit.Millilux); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get Illuminance from Kilolux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromKilolux(double kilolux) + { + double value = (double) kilolux; + return new Illuminance(value, IlluminanceUnit.Kilolux); + } + /// + /// Get Illuminance from Lux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromLux(double lux) + { + double value = (double) lux; + return new Illuminance(value, IlluminanceUnit.Lux); + } + /// + /// Get Illuminance from Megalux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromMegalux(double megalux) + { + double value = (double) megalux; + return new Illuminance(value, IlluminanceUnit.Megalux); + } + /// + /// Get Illuminance from Millilux. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Illuminance FromMillilux(double millilux) + { + double value = (double) millilux; + return new Illuminance(value, IlluminanceUnit.Millilux); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +294,345 @@ public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Illuminance Parse(string str, [CanBeNull] string cultureName) + public static Illuminance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IlluminanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromLux(x.Lux + y.Lux)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Illuminance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static IlluminanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static IlluminanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == IlluminanceUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IlluminanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Illuminance to another Illuminance with the unit representation . + /// + /// A Illuminance with the specified unit. + public Illuminance ToUnit(IlluminanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Illuminance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IlluminanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(IlluminanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + 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.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs index a976942c87..8e51a2ef3f 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Information + public sealed partial class Information : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly InformationUnit? _unit; + static Information() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit Bit. /// @@ -75,28 +80,529 @@ public Information() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Information(decimal numericValue, InformationUnit unit) + { + if(unit == InformationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Information, which is Bit. All conversions go via this value. + /// + public static InformationUnit BaseUnit => InformationUnit.Bit; + + /// + /// Represents the largest possible value of Information + /// + public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Information + /// + public static Information MinValue => new Information(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Information; + + /// + /// All units of measurement for the Information quantity. + /// + public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Bit. + /// + public static Information Zero => new Information(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Information.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Information.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Information in Bits. + /// + public double Bits => As(InformationUnit.Bit); + + /// + /// Get Information in Bytes. + /// + public double Bytes => As(InformationUnit.Byte); + + /// + /// Get Information in Exabits. + /// + public double Exabits => As(InformationUnit.Exabit); + + /// + /// Get Information in Exabytes. + /// + public double Exabytes => As(InformationUnit.Exabyte); + + /// + /// Get Information in Exbibits. + /// + public double Exbibits => As(InformationUnit.Exbibit); + + /// + /// Get Information in Exbibytes. + /// + public double Exbibytes => As(InformationUnit.Exbibyte); + + /// + /// Get Information in Gibibits. + /// + public double Gibibits => As(InformationUnit.Gibibit); + + /// + /// Get Information in Gibibytes. + /// + public double Gibibytes => As(InformationUnit.Gibibyte); + + /// + /// Get Information in Gigabits. + /// + public double Gigabits => As(InformationUnit.Gigabit); + + /// + /// Get Information in Gigabytes. + /// + public double Gigabytes => As(InformationUnit.Gigabyte); + + /// + /// Get Information in Kibibits. + /// + public double Kibibits => As(InformationUnit.Kibibit); + + /// + /// Get Information in Kibibytes. + /// + public double Kibibytes => As(InformationUnit.Kibibyte); + + /// + /// Get Information in Kilobits. + /// + public double Kilobits => As(InformationUnit.Kilobit); + + /// + /// Get Information in Kilobytes. + /// + public double Kilobytes => As(InformationUnit.Kilobyte); + + /// + /// Get Information in Mebibits. + /// + public double Mebibits => As(InformationUnit.Mebibit); + + /// + /// Get Information in Mebibytes. + /// + public double Mebibytes => As(InformationUnit.Mebibyte); + + /// + /// Get Information in Megabits. + /// + public double Megabits => As(InformationUnit.Megabit); + + /// + /// Get Information in Megabytes. + /// + public double Megabytes => As(InformationUnit.Megabyte); + + /// + /// Get Information in Pebibits. + /// + public double Pebibits => As(InformationUnit.Pebibit); + + /// + /// Get Information in Pebibytes. + /// + public double Pebibytes => As(InformationUnit.Pebibyte); + + /// + /// Get Information in Petabits. + /// + public double Petabits => As(InformationUnit.Petabit); + + /// + /// Get Information in Petabytes. + /// + public double Petabytes => As(InformationUnit.Petabyte); + + /// + /// Get Information in Tebibits. + /// + public double Tebibits => As(InformationUnit.Tebibit); + + /// + /// Get Information in Tebibytes. + /// + public double Tebibytes => As(InformationUnit.Tebibyte); + + /// + /// Get Information in Terabits. + /// + public double Terabits => As(InformationUnit.Terabit); + + /// + /// Get Information in Terabytes. + /// + public double Terabytes => As(InformationUnit.Terabyte); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(InformationUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get Information from Bits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromBits(double bits) + { + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); + } + /// + /// Get Information from Bytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromBytes(double bytes) + { + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); + } + /// + /// Get Information from Exabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExabits(double exabits) + { + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); + } + /// + /// Get Information from Exabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExabytes(double exabytes) + { + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); + } + /// + /// Get Information from Exbibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExbibits(double exbibits) + { + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); + } + /// + /// Get Information from Exbibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromExbibytes(double exbibytes) + { + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); + } + /// + /// Get Information from Gibibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGibibits(double gibibits) + { + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); + } + /// + /// Get Information from Gibibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGibibytes(double gibibytes) + { + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); + } + /// + /// Get Information from Gigabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGigabits(double gigabits) + { + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); + } + /// + /// Get Information from Gigabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromGigabytes(double gigabytes) + { + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); + } + /// + /// Get Information from Kibibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKibibits(double kibibits) + { + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); + } + /// + /// Get Information from Kibibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKibibytes(double kibibytes) + { + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); + } + /// + /// Get Information from Kilobits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKilobits(double kilobits) + { + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); + } + /// + /// Get Information from Kilobytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromKilobytes(double kilobytes) + { + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); + } + /// + /// Get Information from Mebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMebibits(double mebibits) + { + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); + } + /// + /// Get Information from Mebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMebibytes(double mebibytes) + { + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); + } + /// + /// Get Information from Megabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMegabits(double megabits) + { + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); + } + /// + /// Get Information from Megabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromMegabytes(double megabytes) + { + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); + } + /// + /// Get Information from Pebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPebibits(double pebibits) + { + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); + } + /// + /// Get Information from Pebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPebibytes(double pebibytes) + { + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); + } + /// + /// Get Information from Petabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPetabits(double petabits) + { + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); + } + /// + /// Get Information from Petabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromPetabytes(double petabytes) + { + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); + } + /// + /// Get Information from Tebibits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTebibits(double tebibits) + { + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); + } + /// + /// Get Information from Tebibytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTebibytes(double tebibytes) + { + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); + } + /// + /// Get Information from Terabits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTerabits(double terabits) + { + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); + } + /// + /// Get Information from Terabytes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Information FromTerabytes(double terabytes) + { + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Information unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Information From(double value, InformationUnit fromUnit) + { + return new Information((decimal)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +621,389 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Information Parse(string str, [CanBeNull] string cultureName) + public static Information Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - InformationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromBits(x.Bits + y.Bits)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Information); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static InformationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static InformationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out InformationUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == InformationUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(InformationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Information to another Information with the unit representation . + /// + /// A Information with the specified unit. + public Information ToUnit(InformationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Information(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(InformationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs index 2fa88e6256..b5bed9e0bc 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Irradiance + public sealed partial class Irradiance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradianceUnit? _unit; + + static Irradiance() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. /// @@ -75,28 +80,169 @@ public Irradiance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Irradiance(double numericValue, IrradianceUnit unit) + { + if(unit == IrradianceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. + /// + public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; + + /// + /// Represents the largest possible value of Irradiance + /// + public static Irradiance MaxValue => new Irradiance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Irradiance + /// + public static Irradiance MinValue => new Irradiance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Irradiance; + + /// + /// All units of measurement for the Irradiance quantity. + /// + public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static Irradiance Zero => new Irradiance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Irradiance in KilowattsPerSquareMeter. + /// + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + + /// + /// Get Irradiance in WattsPerSquareMeter. + /// + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradianceUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiance from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); + } + /// + /// Get Irradiance from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] string cul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Irradiance Parse(string str, [CanBeNull] string cultureName) + public static Irradiance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IrradianceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeter(x.WattsPerSquareMeter + y.WattsPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Irradiance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static IrradianceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static IrradianceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == IrradianceUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradianceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Irradiance to another Irradiance with the unit representation . + /// + /// A Irradiance with the specified unit. + public Irradiance ToUnit(IrradianceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Irradiance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradianceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; + case IrradianceUnit.WattPerSquareMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(IrradianceUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; + case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(IrradianceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs index 0d20227817..3edbfea3ef 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Irradiation : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradiationUnit? _unit; + + static Irradiation() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerSquareMeter. /// @@ -75,28 +83,184 @@ public Irradiation() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Irradiation(double numericValue, IrradiationUnit unit) + { + if(unit == IrradiationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. + /// + public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; + + /// + /// Represents the largest possible value of Irradiation + /// + public static Irradiation MaxValue => new Irradiation(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Irradiation + /// + public static Irradiation MinValue => new Irradiation(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Irradiation; + + /// + /// All units of measurement for the Irradiation quantity. + /// + public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// + public static Irradiation Zero => new Irradiation(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiation.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiation.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Irradiation in JoulesPerSquareMeter. + /// + public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); + + /// + /// Get Irradiation in KilowattHoursPerSquareMeter. + /// + public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); + + /// + /// Get Irradiation in WattHoursPerSquareMeter. + /// + public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get Irradiation from JoulesPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) + { + double value = (double) joulespersquaremeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); + } + /// + /// Get Irradiation from KilowattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) + { + double value = (double) kilowatthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); + } + /// + /// Get Irradiation from WattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) + { + double value = (double) watthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Irradiation unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Irradiation From(double value, IrradiationUnit fromUnit) + { + return new Irradiation((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +279,343 @@ public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Irradiation Parse(string str, [CanBeNull] string cultureName) + public static Irradiation Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IrradiationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerSquareMeter(x.JoulesPerSquareMeter + y.JoulesPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Irradiation); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static IrradiationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static IrradiationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out IrradiationUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == IrradiationUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradiationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Irradiation to another Irradiation with the unit representation . + /// + /// A Irradiation with the specified unit. + public Irradiation ToUnit(IrradiationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Irradiation(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradiationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case IrradiationUnit.JoulePerSquareMeter: return _value; + case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(IrradiationUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; + case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(IrradiationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs index 2419cc1607..f2944f61d5 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class KinematicViscosity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly KinematicViscosityUnit? _unit; + static KinematicViscosity() + { + BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit SquareMeterPerSecond. /// @@ -75,28 +83,259 @@ public KinematicViscosity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private KinematicViscosity(double numericValue, KinematicViscosityUnit unit) + { + if(unit == KinematicViscosityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. + /// + public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; + + /// + /// Represents the largest possible value of KinematicViscosity + /// + public static KinematicViscosity MaxValue => new KinematicViscosity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of KinematicViscosity + /// + public static KinematicViscosity MinValue => new KinematicViscosity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.KinematicViscosity; + + /// + /// All units of measurement for the KinematicViscosity quantity. + /// + public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// + public static KinematicViscosity Zero => new KinematicViscosity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => KinematicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get KinematicViscosity in Centistokes. + /// + public double Centistokes => As(KinematicViscosityUnit.Centistokes); + + /// + /// Get KinematicViscosity in Decistokes. + /// + public double Decistokes => As(KinematicViscosityUnit.Decistokes); + + /// + /// Get KinematicViscosity in Kilostokes. + /// + public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); + + /// + /// Get KinematicViscosity in Microstokes. + /// + public double Microstokes => As(KinematicViscosityUnit.Microstokes); + + /// + /// Get KinematicViscosity in Millistokes. + /// + public double Millistokes => As(KinematicViscosityUnit.Millistokes); + + /// + /// Get KinematicViscosity in Nanostokes. + /// + public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); + + /// + /// Get KinematicViscosity in SquareMetersPerSecond. + /// + public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); + + /// + /// Get KinematicViscosity in Stokes. + /// + public double Stokes => As(KinematicViscosityUnit.Stokes); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get KinematicViscosity from Centistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromCentistokes(double centistokes) + { + double value = (double) centistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); + } + /// + /// Get KinematicViscosity from Decistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromDecistokes(double decistokes) + { + double value = (double) decistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); + } + /// + /// Get KinematicViscosity from Kilostokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromKilostokes(double kilostokes) + { + double value = (double) kilostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); + } + /// + /// Get KinematicViscosity from Microstokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromMicrostokes(double microstokes) + { + double value = (double) microstokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); + } + /// + /// Get KinematicViscosity from Millistokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromMillistokes(double millistokes) + { + double value = (double) millistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); + } + /// + /// Get KinematicViscosity from Nanostokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromNanostokes(double nanostokes) + { + double value = (double) nanostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); + } + /// + /// Get KinematicViscosity from SquareMetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) + { + double value = (double) squaremeterspersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); + } + /// + /// Get KinematicViscosity from Stokes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static KinematicViscosity FromStokes(double stokes) + { + double value = (double) stokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +354,353 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] st /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static KinematicViscosity Parse(string str, [CanBeNull] string cultureName) + public static KinematicViscosity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - KinematicViscosityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMetersPerSecond(x.SquareMetersPerSecond + y.SquareMetersPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(KinematicViscosity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static KinematicViscosityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static KinematicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(KinematicViscosityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == KinematicViscosityUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized KinematicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; + case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; + case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; + case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return _value; + case KinematicViscosityUnit.Stokes: return _value/1e4; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(KinematicViscosityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; + case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; + case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; + case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; + case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(KinematicViscosityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs index baa0846609..1242a38c3d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LapseRate + public sealed partial class LapseRate : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LapseRateUnit? _unit; + + static LapseRate() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. /// @@ -75,28 +80,154 @@ public LapseRate() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private LapseRate(double numericValue, LapseRateUnit unit) + { + if(unit == LapseRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. + /// + public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; + + /// + /// Represents the largest possible value of LapseRate + /// + public static LapseRate MaxValue => new LapseRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LapseRate + /// + public static LapseRate MinValue => new LapseRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LapseRate; + + /// + /// All units of measurement for the LapseRate quantity. + /// + public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. + /// + public static LapseRate Zero => new LapseRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LapseRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LapseRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LapseRate in DegreesCelciusPerKilometer. + /// + public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LapseRateUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LapseRate from DegreesCelciusPerKilometer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) + { + double value = (double) degreescelciusperkilometer; + return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +246,339 @@ public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] string cult /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LapseRate Parse(string str, [CanBeNull] string cultureName) + public static LapseRate Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LapseRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegreesCelciusPerKilometer(x.DegreesCelciusPerKilometer + y.DegreesCelciusPerKilometer)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(LapseRate); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LapseRateUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LapseRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LapseRateUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == LapseRateUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LapseRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LapseRateUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + 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.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs index 0153958518..c3caf25b5d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Length + public sealed partial class Length : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LengthUnit? _unit; + + static Length() + { + BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Meter. /// @@ -75,28 +80,469 @@ public Length() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Length(double numericValue, LengthUnit unit) + { + if(unit == LengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Length, which is Meter. All conversions go via this value. + /// + public static LengthUnit BaseUnit => LengthUnit.Meter; + + /// + /// Represents the largest possible value of Length + /// + public static Length MaxValue => new Length(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Length + /// + public static Length MinValue => new Length(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Length; + + /// + /// All units of measurement for the Length quantity. + /// + public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Meter. + /// + public static Length Zero => new Length(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Length.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Length.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Length in Centimeters. + /// + public double Centimeters => As(LengthUnit.Centimeter); + + /// + /// Get Length in Decimeters. + /// + public double Decimeters => As(LengthUnit.Decimeter); + + /// + /// Get Length in DtpPicas. + /// + public double DtpPicas => As(LengthUnit.DtpPica); + + /// + /// Get Length in DtpPoints. + /// + public double DtpPoints => As(LengthUnit.DtpPoint); + + /// + /// Get Length in Fathoms. + /// + public double Fathoms => As(LengthUnit.Fathom); + + /// + /// Get Length in Feet. + /// + public double Feet => As(LengthUnit.Foot); + + /// + /// Get Length in Inches. + /// + public double Inches => As(LengthUnit.Inch); + + /// + /// Get Length in Kilometers. + /// + public double Kilometers => As(LengthUnit.Kilometer); + + /// + /// Get Length in Meters. + /// + public double Meters => As(LengthUnit.Meter); + + /// + /// Get Length in Microinches. + /// + public double Microinches => As(LengthUnit.Microinch); + + /// + /// Get Length in Micrometers. + /// + public double Micrometers => As(LengthUnit.Micrometer); + + /// + /// Get Length in Mils. + /// + public double Mils => As(LengthUnit.Mil); + + /// + /// Get Length in Miles. + /// + public double Miles => As(LengthUnit.Mile); + + /// + /// Get Length in Millimeters. + /// + public double Millimeters => As(LengthUnit.Millimeter); + + /// + /// Get Length in Nanometers. + /// + public double Nanometers => As(LengthUnit.Nanometer); + + /// + /// Get Length in NauticalMiles. + /// + public double NauticalMiles => As(LengthUnit.NauticalMile); + + /// + /// Get Length in PrinterPicas. + /// + public double PrinterPicas => As(LengthUnit.PrinterPica); + + /// + /// Get Length in PrinterPoints. + /// + public double PrinterPoints => As(LengthUnit.PrinterPoint); + + /// + /// Get Length in Shackles. + /// + public double Shackles => As(LengthUnit.Shackle); + + /// + /// Get Length in Twips. + /// + public double Twips => As(LengthUnit.Twip); + + /// + /// Get Length in UsSurveyFeet. + /// + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + + /// + /// Get Length in Yards. + /// + public double Yards => As(LengthUnit.Yard); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LengthUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LengthUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Length from Centimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromCentimeters(double centimeters) + { + double value = (double) centimeters; + return new Length(value, LengthUnit.Centimeter); + } + /// + /// Get Length from Decimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDecimeters(double decimeters) + { + double value = (double) decimeters; + return new Length(value, LengthUnit.Decimeter); + } + /// + /// Get Length from DtpPicas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDtpPicas(double dtppicas) + { + double value = (double) dtppicas; + return new Length(value, LengthUnit.DtpPica); } + /// + /// Get Length from DtpPoints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromDtpPoints(double dtppoints) + { + double value = (double) dtppoints; + return new Length(value, LengthUnit.DtpPoint); + } + /// + /// Get Length from Fathoms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromFathoms(double fathoms) + { + double value = (double) fathoms; + return new Length(value, LengthUnit.Fathom); + } + /// + /// Get Length from Feet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromFeet(double feet) + { + double value = (double) feet; + return new Length(value, LengthUnit.Foot); + } + /// + /// Get Length from Inches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromInches(double inches) + { + double value = (double) inches; + return new Length(value, LengthUnit.Inch); + } + /// + /// Get Length from Kilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromKilometers(double kilometers) + { + double value = (double) kilometers; + return new Length(value, LengthUnit.Kilometer); + } + /// + /// Get Length from Meters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMeters(double meters) + { + double value = (double) meters; + return new Length(value, LengthUnit.Meter); + } + /// + /// Get Length from Microinches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMicroinches(double microinches) + { + double value = (double) microinches; + return new Length(value, LengthUnit.Microinch); + } + /// + /// Get Length from Micrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMicrometers(double micrometers) + { + double value = (double) micrometers; + return new Length(value, LengthUnit.Micrometer); + } + /// + /// Get Length from Mils. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMils(double mils) + { + double value = (double) mils; + return new Length(value, LengthUnit.Mil); + } + /// + /// Get Length from Miles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMiles(double miles) + { + double value = (double) miles; + return new Length(value, LengthUnit.Mile); + } + /// + /// Get Length from Millimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromMillimeters(double millimeters) + { + double value = (double) millimeters; + return new Length(value, LengthUnit.Millimeter); + } + /// + /// Get Length from Nanometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromNanometers(double nanometers) + { + double value = (double) nanometers; + return new Length(value, LengthUnit.Nanometer); + } + /// + /// Get Length from NauticalMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromNauticalMiles(double nauticalmiles) + { + double value = (double) nauticalmiles; + return new Length(value, LengthUnit.NauticalMile); + } + /// + /// Get Length from PrinterPicas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromPrinterPicas(double printerpicas) + { + double value = (double) printerpicas; + return new Length(value, LengthUnit.PrinterPica); + } + /// + /// Get Length from PrinterPoints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromPrinterPoints(double printerpoints) + { + double value = (double) printerpoints; + return new Length(value, LengthUnit.PrinterPoint); + } + /// + /// Get Length from Shackles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromShackles(double shackles) + { + double value = (double) shackles; + return new Length(value, LengthUnit.Shackle); + } + /// + /// Get Length from Twips. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromTwips(double twips) + { + double value = (double) twips; + return new Length(value, LengthUnit.Twip); + } + /// + /// Get Length from UsSurveyFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromUsSurveyFeet(double ussurveyfeet) + { + double value = (double) ussurveyfeet; + return new Length(value, LengthUnit.UsSurveyFoot); + } + /// + /// Get Length from Yards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Length FromYards(double yards) + { + double value = (double) yards; + return new Length(value, LengthUnit.Yard); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Length unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Length From(double value, LengthUnit fromUnit) + { + return new Length((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +561,381 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] string culture /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Length Parse(string str, [CanBeNull] string cultureName) + public static Length Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMeters(x.Meters + y.Meters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Length); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LengthUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #region Conversion Methods - if (unit == LengthUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LengthUnit.Centimeter: return (_value) * 1e-2d; + case LengthUnit.Decimeter: return (_value) * 1e-1d; + case LengthUnit.DtpPica: return _value/236.220472441; + case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; + case LengthUnit.Fathom: return _value*1.8288; + case LengthUnit.Foot: return _value*0.3048; + case LengthUnit.Inch: return _value*2.54e-2; + case LengthUnit.Kilometer: return (_value) * 1e3d; + case LengthUnit.Meter: return _value; + case LengthUnit.Microinch: return _value*2.54e-8; + case LengthUnit.Micrometer: return (_value) * 1e-6d; + case LengthUnit.Mil: return _value*2.54e-5; + case LengthUnit.Mile: return _value*1609.34; + case LengthUnit.Millimeter: return (_value) * 1e-3d; + case LengthUnit.Nanometer: return (_value) * 1e-9d; + case LengthUnit.NauticalMile: return _value*1852; + case LengthUnit.PrinterPica: return _value/237.106301584; + case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; + case LengthUnit.Shackle: return _value*27.432; + case LengthUnit.Twip: return _value/56692.913385826; + case LengthUnit.UsSurveyFoot: return _value*1200/3937; + case LengthUnit.Yard: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(LengthUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; + case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; + case LengthUnit.DtpPica: return baseUnitValue*236.220472441; + case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; + case LengthUnit.Fathom: return baseUnitValue/1.8288; + case LengthUnit.Foot: return baseUnitValue/0.3048; + case LengthUnit.Inch: return baseUnitValue/2.54e-2; + case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; + case LengthUnit.Meter: return baseUnitValue; + case LengthUnit.Microinch: return baseUnitValue/2.54e-8; + case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; + case LengthUnit.Mil: return baseUnitValue/2.54e-5; + case LengthUnit.Mile: return baseUnitValue/1609.34; + case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; + case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; + case LengthUnit.NauticalMile: return baseUnitValue/1852; + case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; + case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; + case LengthUnit.Shackle: return baseUnitValue/27.432; + case LengthUnit.Twip: return baseUnitValue*56692.913385826; + case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; + case LengthUnit.Yard: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LengthUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + 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.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs index da2464eb8b..67f61d03d0 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Level + public sealed partial class Level : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LevelUnit? _unit; + + static Level() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit Decibel. /// @@ -75,28 +80,169 @@ public Level() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Level(double numericValue, LevelUnit unit) + { + if(unit == LevelUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Level, which is Decibel. All conversions go via this value. + /// + public static LevelUnit BaseUnit => LevelUnit.Decibel; + + /// + /// Represents the largest possible value of Level + /// + public static Level MaxValue => new Level(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Level + /// + public static Level MinValue => new Level(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Level; + + /// + /// All units of measurement for the Level quantity. + /// + public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. + /// + public static Level Zero => new Level(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Level.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Level.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Level in Decibels. + /// + public double Decibels => As(LevelUnit.Decibel); + + /// + /// Get Level in Nepers. + /// + public double Nepers => As(LevelUnit.Neper); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LevelUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Level from Decibels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Level FromDecibels(double decibels) + { + double value = (double) decibels; + return new Level(value, LevelUnit.Decibel); + } + /// + /// Get Level from Nepers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Level FromNepers(double nepers) + { + double value = (double) nepers; + return new Level(value, LevelUnit.Neper); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Level Parse(string str, [CanBeNull] string cultureName) + public static Level Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LevelUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibels(x.Decibels + y.Decibels)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Level); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LevelUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LevelUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == LevelUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LevelUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Level to another Level with the unit representation . + /// + /// A Level with the specified unit. + public Level ToUnit(LevelUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Level(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LevelUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs index 581e09735a..7dad64c701 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class LinearDensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LinearDensityUnit? _unit; + + static LinearDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerMeter. /// @@ -75,28 +83,184 @@ public LinearDensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private LinearDensity(double numericValue, LinearDensityUnit unit) + { + if(unit == LinearDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. + /// + public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; + + /// + /// Represents the largest possible value of LinearDensity + /// + public static LinearDensity MaxValue => new LinearDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LinearDensity + /// + public static LinearDensity MinValue => new LinearDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LinearDensity; + + /// + /// All units of measurement for the LinearDensity quantity. + /// + public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. + /// + public static LinearDensity Zero => new LinearDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LinearDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LinearDensity in GramsPerMeter. + /// + public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); + + /// + /// Get LinearDensity in KilogramsPerMeter. + /// + public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); + + /// + /// Get LinearDensity in PoundsPerFoot. + /// + public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get LinearDensity from GramsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromGramsPerMeter(double gramspermeter) + { + double value = (double) gramspermeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); + } + /// + /// Get LinearDensity from KilogramsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) + { + double value = (double) kilogramspermeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); + } + /// + /// Get LinearDensity from PoundsPerFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LinearDensity FromPoundsPerFoot(double poundsperfoot) + { + double value = (double) poundsperfoot; + return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// LinearDensity unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static LinearDensity From(double value, LinearDensityUnit fromUnit) + { + return new LinearDensity((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +279,343 @@ public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LinearDensity Parse(string str, [CanBeNull] string cultureName) + public static LinearDensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LinearDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerMeter(x.KilogramsPerMeter + y.KilogramsPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(LinearDensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LinearDensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LinearDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out LinearDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == LinearDensityUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LinearDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this LinearDensity to another LinearDensity with the unit representation . + /// + /// A LinearDensity with the specified unit. + public LinearDensity ToUnit(LinearDensityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new LinearDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LinearDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LinearDensityUnit.GramPerMeter: return _value*1e-3; + case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; + case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(LinearDensityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; + case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; + case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LinearDensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs index 1d4f6a0277..9d867e79a5 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class LuminousFlux : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousFluxUnit? _unit; + + static LuminousFlux() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } /// /// Creates the quantity with a value of 0 in the base unit Lumen. /// @@ -75,28 +83,154 @@ public LuminousFlux() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private LuminousFlux(double numericValue, LuminousFluxUnit unit) + { + if(unit == LuminousFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. + /// + public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; + + /// + /// Represents the largest possible value of LuminousFlux + /// + public static LuminousFlux MaxValue => new LuminousFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LuminousFlux + /// + public static LuminousFlux MinValue => new LuminousFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LuminousFlux; + + /// + /// All units of measurement for the LuminousFlux quantity. + /// + public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. + /// + public static LuminousFlux Zero => new LuminousFlux(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousFlux in Lumens. + /// + public double Lumens => As(LuminousFluxUnit.Lumen); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousFlux from Lumens. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LuminousFlux FromLumens(double lumens) + { + double value = (double) lumens; + return new LuminousFlux(value, LuminousFluxUnit.Lumen); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LuminousFlux Parse(string str, [CanBeNull] string cultureName) + public static LuminousFlux Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LuminousFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromLumens(x.Lumens + y.Lumens)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(LuminousFlux); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LuminousFluxUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LuminousFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousFluxUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == LuminousFluxUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LuminousFluxUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs index a2f7408e30..6ba10e506e 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class LuminousIntensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousIntensityUnit? _unit; + + static LuminousIntensity() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } /// /// Creates the quantity with a value of 0 in the base unit Candela. /// @@ -75,28 +83,154 @@ public LuminousIntensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private LuminousIntensity(double numericValue, LuminousIntensityUnit unit) + { + if(unit == LuminousIntensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. + /// + public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; + + /// + /// Represents the largest possible value of LuminousIntensity + /// + public static LuminousIntensity MaxValue => new LuminousIntensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LuminousIntensity + /// + public static LuminousIntensity MinValue => new LuminousIntensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LuminousIntensity; + + /// + /// All units of measurement for the LuminousIntensity quantity. + /// + public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Candela. + /// + public static LuminousIntensity Zero => new LuminousIntensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousIntensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousIntensity in Candela. + /// + public double Candela => As(LuminousIntensityUnit.Candela); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousIntensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get LuminousIntensity from Candela. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static LuminousIntensity FromCandela(double candela) + { + double value = (double) candela; + return new LuminousIntensity(value, LuminousIntensityUnit.Candela); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] str /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LuminousIntensity Parse(string str, [CanBeNull] string cultureName) + public static LuminousIntensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LuminousIntensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCandela(x.Candela + y.Candela)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(LuminousIntensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static LuminousIntensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static LuminousIntensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousIntensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == LuminousIntensityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousIntensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(LuminousIntensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs index ccf856bbf4..86caad02ba 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class MagneticField : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFieldUnit? _unit; + + static MagneticField() + { + BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Tesla. /// @@ -75,28 +83,199 @@ public MagneticField() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MagneticField(double numericValue, MagneticFieldUnit unit) + { + if(unit == MagneticFieldUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticField, which is Tesla. All conversions go via this value. + /// + public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; + + /// + /// Represents the largest possible value of MagneticField + /// + public static MagneticField MaxValue => new MagneticField(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MagneticField + /// + public static MagneticField MinValue => new MagneticField(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MagneticField; + + /// + /// All units of measurement for the MagneticField quantity. + /// + public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. + /// + public static MagneticField Zero => new MagneticField(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticField in Microteslas. + /// + public double Microteslas => As(MagneticFieldUnit.Microtesla); + + /// + /// Get MagneticField in Milliteslas. + /// + public double Milliteslas => As(MagneticFieldUnit.Millitesla); + + /// + /// Get MagneticField in Nanoteslas. + /// + public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); + + /// + /// Get MagneticField in Teslas. + /// + public double Teslas => As(MagneticFieldUnit.Tesla); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MagneticField from Microteslas. + /// + /// 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); + } + /// + /// Get MagneticField from Milliteslas. + /// + /// 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); + } + /// + /// Get MagneticField from Nanoteslas. + /// + /// 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); + } + /// + /// Get MagneticField from Teslas. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MagneticField FromTeslas(double teslas) + { + double value = (double) teslas; + return new MagneticField(value, MagneticFieldUnit.Tesla); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +294,345 @@ public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MagneticField Parse(string str, [CanBeNull] string cultureName) + public static MagneticField Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagneticFieldUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromTeslas(x.Teslas + y.Teslas)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MagneticField); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MagneticFieldUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MagneticFieldUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == MagneticFieldUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFieldUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MagneticField to another MagneticField with the unit representation . + /// + /// A MagneticField with the specified unit. + public MagneticField ToUnit(MagneticFieldUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MagneticField(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MagneticFieldUnit.Microtesla: return (_value) * 1e-6d; + 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."); } + } - return unit; + private double AsBaseNumericType(MagneticFieldUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case MagneticFieldUnit.Microtesla: return (baseUnitValue) / 1e-6d; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MagneticFieldUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs index 99daf87c26..ba0b4d1bb1 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class MagneticFlux : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFluxUnit? _unit; + + static MagneticFlux() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Weber. /// @@ -75,28 +83,154 @@ public MagneticFlux() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MagneticFlux(double numericValue, MagneticFluxUnit unit) + { + if(unit == MagneticFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. + /// + public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; + + /// + /// Represents the largest possible value of MagneticFlux + /// + public static MagneticFlux MaxValue => new MagneticFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MagneticFlux + /// + public static MagneticFlux MinValue => new MagneticFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MagneticFlux; + + /// + /// All units of measurement for the MagneticFlux quantity. + /// + public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Weber. + /// + public static MagneticFlux Zero => new MagneticFlux(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticFlux in Webers. + /// + public double Webers => As(MagneticFluxUnit.Weber); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticFlux from Webers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MagneticFlux FromWebers(double webers) + { + double value = (double) webers; + return new MagneticFlux(value, MagneticFluxUnit.Weber); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MagneticFlux Parse(string str, [CanBeNull] string cultureName) + public static MagneticFlux Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagneticFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWebers(x.Webers + y.Webers)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MagneticFlux); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MagneticFluxUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MagneticFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFluxUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == MagneticFluxUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MagneticFluxUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs index cadd0acb99..0c3a26cf2d 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Magnetization : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MagnetizationUnit? _unit; + + static Magnetization() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit AmperePerMeter. /// @@ -75,28 +83,154 @@ public Magnetization() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Magnetization(double numericValue, MagnetizationUnit unit) + { + if(unit == MagnetizationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. + /// + public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; + + /// + /// Represents the largest possible value of Magnetization + /// + public static Magnetization MaxValue => new Magnetization(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Magnetization + /// + public static Magnetization MinValue => new Magnetization(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Magnetization; + + /// + /// All units of measurement for the Magnetization quantity. + /// + public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. + /// + public static Magnetization Zero => new Magnetization(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Magnetization.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Magnetization.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Magnetization in AmperesPerMeter. + /// + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagnetizationUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Magnetization from AmperesPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Magnetization FromAmperesPerMeter(double amperespermeter) + { + double value = (double) amperespermeter; + return new Magnetization(value, MagnetizationUnit.AmperePerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Magnetization Parse(string str, [CanBeNull] string cultureName) + public static Magnetization Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagnetizationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerMeter(x.AmperesPerMeter + y.AmperesPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Magnetization); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MagnetizationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MagnetizationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagnetizationUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == MagnetizationUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagnetizationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MagnetizationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs index 8be9a9df40..f6b75df0f3 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Mass + public sealed partial class Mass : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MassUnit? _unit; + + static Mass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Kilogram. /// @@ -75,28 +80,469 @@ public Mass() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Mass(double numericValue, MassUnit unit) + { + if(unit == MassUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Mass, which is Kilogram. All conversions go via this value. + /// + public static MassUnit BaseUnit => MassUnit.Kilogram; + + /// + /// Represents the largest possible value of Mass + /// + public static Mass MaxValue => new Mass(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Mass + /// + public static Mass MinValue => new Mass(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Mass; + + /// + /// All units of measurement for the Mass quantity. + /// + public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. + /// + public static Mass Zero => new Mass(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Mass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Mass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Mass in Centigrams. + /// + public double Centigrams => As(MassUnit.Centigram); + + /// + /// Get Mass in Decagrams. + /// + public double Decagrams => As(MassUnit.Decagram); + + /// + /// Get Mass in Decigrams. + /// + public double Decigrams => As(MassUnit.Decigram); + + /// + /// Get Mass in Grams. + /// + public double Grams => As(MassUnit.Gram); + + /// + /// Get Mass in Hectograms. + /// + public double Hectograms => As(MassUnit.Hectogram); + + /// + /// Get Mass in Kilograms. + /// + public double Kilograms => As(MassUnit.Kilogram); + + /// + /// Get Mass in Kilopounds. + /// + public double Kilopounds => As(MassUnit.Kilopound); + + /// + /// Get Mass in Kilotonnes. + /// + public double Kilotonnes => As(MassUnit.Kilotonne); + + /// + /// Get Mass in LongHundredweight. + /// + public double LongHundredweight => As(MassUnit.LongHundredweight); + + /// + /// Get Mass in LongTons. + /// + public double LongTons => As(MassUnit.LongTon); + + /// + /// Get Mass in Megapounds. + /// + public double Megapounds => As(MassUnit.Megapound); + + /// + /// Get Mass in Megatonnes. + /// + public double Megatonnes => As(MassUnit.Megatonne); + + /// + /// Get Mass in Micrograms. + /// + public double Micrograms => As(MassUnit.Microgram); + + /// + /// Get Mass in Milligrams. + /// + public double Milligrams => As(MassUnit.Milligram); + + /// + /// Get Mass in Nanograms. + /// + public double Nanograms => As(MassUnit.Nanogram); + + /// + /// Get Mass in Ounces. + /// + public double Ounces => As(MassUnit.Ounce); + + /// + /// Get Mass in Pounds. + /// + public double Pounds => As(MassUnit.Pound); + + /// + /// Get Mass in ShortHundredweight. + /// + public double ShortHundredweight => As(MassUnit.ShortHundredweight); + + /// + /// Get Mass in ShortTons. + /// + public double ShortTons => As(MassUnit.ShortTon); + + /// + /// Get Mass in Slugs. + /// + public double Slugs => As(MassUnit.Slug); + + /// + /// Get Mass in Stone. + /// + public double Stone => As(MassUnit.Stone); + + /// + /// Get Mass in Tonnes. + /// + public double Tonnes => As(MassUnit.Tonne); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(MassUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Mass from Centigrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromCentigrams(double centigrams) + { + double value = (double) centigrams; + return new Mass(value, MassUnit.Centigram); + } + /// + /// Get Mass from Decagrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromDecagrams(double decagrams) + { + double value = (double) decagrams; + return new Mass(value, MassUnit.Decagram); + } + /// + /// Get Mass from Decigrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromDecigrams(double decigrams) + { + double value = (double) decigrams; + return new Mass(value, MassUnit.Decigram); } + /// + /// Get Mass from Grams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromGrams(double grams) + { + double value = (double) grams; + return new Mass(value, MassUnit.Gram); + } + /// + /// Get Mass from Hectograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromHectograms(double hectograms) + { + double value = (double) hectograms; + return new Mass(value, MassUnit.Hectogram); + } + /// + /// Get Mass from Kilograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilograms(double kilograms) + { + double value = (double) kilograms; + return new Mass(value, MassUnit.Kilogram); + } + /// + /// Get Mass from Kilopounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilopounds(double kilopounds) + { + double value = (double) kilopounds; + return new Mass(value, MassUnit.Kilopound); + } + /// + /// Get Mass from Kilotonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromKilotonnes(double kilotonnes) + { + double value = (double) kilotonnes; + return new Mass(value, MassUnit.Kilotonne); + } + /// + /// Get Mass from LongHundredweight. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromLongHundredweight(double longhundredweight) + { + double value = (double) longhundredweight; + return new Mass(value, MassUnit.LongHundredweight); + } + /// + /// Get Mass from LongTons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromLongTons(double longtons) + { + double value = (double) longtons; + return new Mass(value, MassUnit.LongTon); + } + /// + /// Get Mass from Megapounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMegapounds(double megapounds) + { + double value = (double) megapounds; + return new Mass(value, MassUnit.Megapound); + } + /// + /// Get Mass from Megatonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMegatonnes(double megatonnes) + { + double value = (double) megatonnes; + return new Mass(value, MassUnit.Megatonne); + } + /// + /// Get Mass from Micrograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMicrograms(double micrograms) + { + double value = (double) micrograms; + return new Mass(value, MassUnit.Microgram); + } + /// + /// Get Mass from Milligrams. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromMilligrams(double milligrams) + { + double value = (double) milligrams; + return new Mass(value, MassUnit.Milligram); + } + /// + /// Get Mass from Nanograms. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromNanograms(double nanograms) + { + double value = (double) nanograms; + return new Mass(value, MassUnit.Nanogram); + } + /// + /// Get Mass from Ounces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromOunces(double ounces) + { + double value = (double) ounces; + return new Mass(value, MassUnit.Ounce); + } + /// + /// Get Mass from Pounds. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromPounds(double pounds) + { + double value = (double) pounds; + return new Mass(value, MassUnit.Pound); + } + /// + /// Get Mass from ShortHundredweight. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromShortHundredweight(double shorthundredweight) + { + double value = (double) shorthundredweight; + return new Mass(value, MassUnit.ShortHundredweight); + } + /// + /// Get Mass from ShortTons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromShortTons(double shorttons) + { + double value = (double) shorttons; + return new Mass(value, MassUnit.ShortTon); + } + /// + /// Get Mass from Slugs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromSlugs(double slugs) + { + double value = (double) slugs; + return new Mass(value, MassUnit.Slug); + } + /// + /// Get Mass from Stone. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromStone(double stone) + { + double value = (double) stone; + return new Mass(value, MassUnit.Stone); + } + /// + /// Get Mass from Tonnes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Mass FromTonnes(double tonnes) + { + double value = (double) tonnes; + return new Mass(value, MassUnit.Tonne); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Mass unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Mass From(double value, MassUnit fromUnit) + { + return new Mass((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +561,381 @@ public static string GetAbbreviation(MassUnit unit, [CanBeNull] string cultureNa /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Mass Parse(string str, [CanBeNull] string cultureName) + public static Mass Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilograms(x.Kilograms + y.Kilograms)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Mass); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MassUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MassUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #region Conversion Methods - if (unit == MassUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassUnit.Centigram: return (_value/1e3) * 1e-2d; + case MassUnit.Decagram: return (_value/1e3) * 1e1d; + case MassUnit.Decigram: return (_value/1e3) * 1e-1d; + case MassUnit.Gram: return _value/1e3; + case MassUnit.Hectogram: return (_value/1e3) * 1e2d; + case MassUnit.Kilogram: return (_value/1e3) * 1e3d; + case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; + case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; + case MassUnit.LongHundredweight: return _value/0.01968413055222121; + case MassUnit.LongTon: return _value*1.0160469088e3; + case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; + case MassUnit.Megatonne: return (_value*1e3) * 1e6d; + case MassUnit.Microgram: return (_value/1e3) * 1e-6d; + case MassUnit.Milligram: return (_value/1e3) * 1e-3d; + case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; + case MassUnit.Ounce: return _value/35.2739619; + case MassUnit.Pound: return _value*0.45359237; + case MassUnit.ShortHundredweight: return _value/0.022046226218487758; + case MassUnit.ShortTon: return _value*9.0718474e2; + case MassUnit.Slug: return _value/6.852176556196105e-2; + case MassUnit.Stone: return _value/0.1574731728702698; + case MassUnit.Tonne: return _value*1e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(MassUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; + case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; + case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; + case MassUnit.Gram: return baseUnitValue*1e3; + case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; + case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; + case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; + case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; + case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; + case MassUnit.LongTon: return baseUnitValue/1.0160469088e3; + case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; + case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; + case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; + case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; + case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; + case MassUnit.Ounce: return baseUnitValue*35.2739619; + case MassUnit.Pound: return baseUnitValue/0.45359237; + case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; + case MassUnit.ShortTon: return baseUnitValue/9.0718474e2; + case MassUnit.Slug: return baseUnitValue*6.852176556196105e-2; + case MassUnit.Stone: return baseUnitValue*0.1574731728702698; + case MassUnit.Tonne: return baseUnitValue/1e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MassUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs index a83681536d..eb8c784ec5 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassFlow + public sealed partial class MassFlow : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFlowUnit? _unit; + static MassFlow() + { + BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit GramPerSecond. /// @@ -75,28 +80,409 @@ public MassFlow() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MassFlow(double numericValue, MassFlowUnit unit) + { + if(unit == MassFlowUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. + /// + public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; + + /// + /// Represents the largest possible value of MassFlow + /// + public static MassFlow MaxValue => new MassFlow(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassFlow + /// + public static MassFlow MinValue => new MassFlow(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassFlow; + + /// + /// All units of measurement for the MassFlow quantity. + /// + public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. + /// + public static MassFlow Zero => new MassFlow(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassFlow in CentigramsPerSecond. + /// + public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); + + /// + /// Get MassFlow in DecagramsPerSecond. + /// + public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); + + /// + /// Get MassFlow in DecigramsPerSecond. + /// + public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); + + /// + /// Get MassFlow in GramsPerSecond. + /// + public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); + + /// + /// Get MassFlow in HectogramsPerSecond. + /// + public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); + + /// + /// Get MassFlow in KilogramsPerHour. + /// + public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); + + /// + /// Get MassFlow in KilogramsPerMinute. + /// + public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); + + /// + /// Get MassFlow in KilogramsPerSecond. + /// + public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); + + /// + /// Get MassFlow in MegapoundsPerHour. + /// + public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); + + /// + /// Get MassFlow in MegapoundsPerMinute. + /// + public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + + /// + /// Get MassFlow in MicrogramsPerSecond. + /// + public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); + + /// + /// Get MassFlow in MilligramsPerSecond. + /// + public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); + + /// + /// Get MassFlow in NanogramsPerSecond. + /// + public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); + + /// + /// Get MassFlow in PoundsPerHour. + /// + public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); + + /// + /// Get MassFlow in PoundsPerMinute. + /// + public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + + /// + /// Get MassFlow in ShortTonsPerHour. + /// + public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); + + /// + /// Get MassFlow in TonnesPerDay. + /// + public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); + + /// + /// Get MassFlow in TonnesPerHour. + /// + public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MassFlow from CentigramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromCentigramsPerSecond(double centigramspersecond) + { + double value = (double) centigramspersecond; + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); + } + /// + /// Get MassFlow from DecagramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromDecagramsPerSecond(double decagramspersecond) + { + double value = (double) decagramspersecond; + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); + } + /// + /// Get MassFlow from DecigramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromDecigramsPerSecond(double decigramspersecond) + { + double value = (double) decigramspersecond; + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); + } + /// + /// Get MassFlow from GramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromGramsPerSecond(double gramspersecond) + { + double value = (double) gramspersecond; + return new MassFlow(value, MassFlowUnit.GramPerSecond); + } + /// + /// Get MassFlow from HectogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) + { + double value = (double) hectogramspersecond; + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); + } + /// + /// Get MassFlow from KilogramsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromKilogramsPerHour(double kilogramsperhour) + { + double value = (double) kilogramsperhour; + return new MassFlow(value, MassFlowUnit.KilogramPerHour); + } + /// + /// Get MassFlow from KilogramsPerMinute. + /// + /// 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); + } + /// + /// Get MassFlow from KilogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) + { + double value = (double) kilogramspersecond; + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); + } + /// + /// Get MassFlow from MegapoundsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) + { + double value = (double) megapoundsperhour; + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); + } + /// + /// Get MassFlow from MegapoundsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMegapoundsPerMinute(double megapoundsperminute) + { + double value = (double) megapoundsperminute; + return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); + } + /// + /// Get MassFlow from MicrogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) + { + double value = (double) microgramspersecond; + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); + } + /// + /// Get MassFlow from MilligramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromMilligramsPerSecond(double milligramspersecond) + { + double value = (double) milligramspersecond; + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); + } + /// + /// Get MassFlow from NanogramsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) + { + double value = (double) nanogramspersecond; + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); + } + /// + /// Get MassFlow from PoundsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromPoundsPerHour(double poundsperhour) + { + double value = (double) poundsperhour; + return new MassFlow(value, MassFlowUnit.PoundPerHour); + } + /// + /// Get MassFlow from PoundsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromPoundsPerMinute(double poundsperminute) + { + double value = (double) poundsperminute; + return new MassFlow(value, MassFlowUnit.PoundPerMinute); + } + /// + /// Get MassFlow from ShortTonsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromShortTonsPerHour(double shorttonsperhour) + { + double value = (double) shorttonsperhour; + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); + } + /// + /// Get MassFlow from TonnesPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromTonnesPerDay(double tonnesperday) + { + double value = (double) tonnesperday; + return new MassFlow(value, MassFlowUnit.TonnePerDay); + } + /// + /// Get MassFlow from TonnesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlow FromTonnesPerHour(double tonnesperhour) + { + double value = (double) tonnesperhour; + return new MassFlow(value, MassFlowUnit.TonnePerHour); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// MassFlow unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MassFlow From(double value, MassFlowUnit fromUnit) + { + return new MassFlow((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +501,373 @@ public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassFlow Parse(string str, [CanBeNull] string cultureName) + public static MassFlow Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassFlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromGramsPerSecond(x.GramsPerSecond + y.GramsPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MassFlow); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MassFlowUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MassFlowUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == MassFlowUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassFlow. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFlowUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MassFlow to another MassFlow with the unit representation . + /// + /// A MassFlow with the specified unit. + public MassFlow ToUnit(MassFlowUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MassFlow(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; + case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; + case MassFlowUnit.GramPerSecond: return _value; + case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; + case MassFlowUnit.KilogramPerHour: return _value/3.6; + case MassFlowUnit.KilogramPerMinute: return _value/0.06; + case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; + case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; + case MassFlowUnit.MegapoundPerMinute: return (_value/0.132277) * 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; + case MassFlowUnit.PoundPerHour: return _value/7.93664; + case MassFlowUnit.PoundPerMinute: return _value/0.132277; + case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; + case MassFlowUnit.TonnePerDay: return _value/0.0864000; + case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(MassFlowUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; + case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; + case MassFlowUnit.GramPerSecond: return baseUnitValue; + case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; + case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; + case MassFlowUnit.KilogramPerMinute: return baseUnitValue*0.06; + case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; + case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; + case MassFlowUnit.MegapoundPerMinute: return (baseUnitValue*0.132277) / 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; + case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; + case MassFlowUnit.PoundPerMinute: return baseUnitValue*0.132277; + case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; + case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; + case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MassFlowUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs index 011f10d707..32a8c1697c 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Mass flux is the mass flow rate per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassFlux + public sealed partial class MassFlux : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFluxUnit? _unit; + + static MassFlux() + { + BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. /// @@ -75,28 +80,169 @@ public MassFlux() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MassFlux(double numericValue, MassFluxUnit unit) + { + if(unit == MassFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. + /// + public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; + + /// + /// Represents the largest possible value of MassFlux + /// + public static MassFlux MaxValue => new MassFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassFlux + /// + public static MassFlux MinValue => new MassFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassFlux; + + /// + /// All units of measurement for the MassFlux quantity. + /// + public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// + public static MassFlux Zero => new MassFlux(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassFlux in GramsPerSecondPerSquareMeter. + /// + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + + /// + /// Get MassFlux in KilogramsPerSecondPerSquareMeter. + /// + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlux from GramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) + { + double value = (double) gramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); + } + /// + /// Get MassFlux from KilogramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) + { + double value = (double) kilogramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassFlux Parse(string str, [CanBeNull] string cultureName) + public static MassFlux Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerSecondPerSquareMeter(x.KilogramsPerSecondPerSquareMeter + y.KilogramsPerSecondPerSquareMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MassFlux); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MassFluxUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MassFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == MassFluxUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MassFlux to another MassFlux with the unit representation . + /// + /// A MassFlux with the specified unit. + public MassFlux ToUnit(MassFluxUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MassFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(MassFluxUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MassFluxUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs index a3002b38e7..39191b30f7 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// A property of body reflects how its mass is distributed with regard to an axis. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassMomentOfInertia + public sealed partial class MassMomentOfInertia : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MassMomentOfInertiaUnit? _unit; + + static MassMomentOfInertia() + { + BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramSquareMeter. /// @@ -75,28 +80,559 @@ public MassMomentOfInertia() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MassMomentOfInertia(double numericValue, MassMomentOfInertiaUnit unit) + { + if(unit == MassMomentOfInertiaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. + /// + public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; + + /// + /// Represents the largest possible value of MassMomentOfInertia + /// + public static MassMomentOfInertia MaxValue => new MassMomentOfInertia(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassMomentOfInertia + /// + public static MassMomentOfInertia MinValue => new MassMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassMomentOfInertia; + + /// + /// All units of measurement for the MassMomentOfInertia quantity. + /// + public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. + /// + public static MassMomentOfInertia Zero => new MassMomentOfInertia(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassMomentOfInertia in GramSquareCentimeters. + /// + public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in GramSquareDecimeters. + /// + public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in GramSquareMeters. + /// + public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); + + /// + /// Get MassMomentOfInertia in GramSquareMillimeters. + /// + public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareCentimeters. + /// + public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareDecimeters. + /// + public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareMeters. + /// + public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareMillimeters. + /// + public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareCentimeters. + /// + public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareDecimeters. + /// + public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareMeters. + /// + public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareMilimeters. + /// + public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareCentimeters. + /// + public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareDecimeters. + /// + public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareMeters. + /// + public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareMilimeters. + /// + public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareCentimeters. + /// + public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareDecimeters. + /// + public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareMeters. + /// + public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareMillimeters. + /// + public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in PoundSquareFeet. + /// + public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); + + /// + /// Get MassMomentOfInertia in PoundSquareInches. + /// + public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); + + /// + /// Get MassMomentOfInertia in SlugSquareFeet. + /// + public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); + + /// + /// Get MassMomentOfInertia in SlugSquareInches. + /// + public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); + + /// + /// Get MassMomentOfInertia in TonneSquareCentimeters. + /// + public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in TonneSquareDecimeters. + /// + public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in TonneSquareMeters. + /// + public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); + + /// + /// Get MassMomentOfInertia in TonneSquareMilimeters. + /// + public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MassMomentOfInertia from GramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) + { + double value = (double) gramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) + { + double value = (double) gramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) + { + double value = (double) gramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); + } + /// + /// Get MassMomentOfInertia from GramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) + { + double value = (double) gramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) + { + double value = (double) kilogramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) + { + double value = (double) kilogramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) + { + double value = (double) kilogramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilogramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) + { + double value = (double) kilogramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) + { + double value = (double) kilotonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); } + /// + /// Get MassMomentOfInertia from KilotonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) + { + double value = (double) kilotonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) + { + double value = (double) kilotonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from KilotonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) + { + double value = (double) kilotonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) + { + double value = (double) megatonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) + { + double value = (double) megatonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) + { + double value = (double) megatonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from MegatonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) + { + double value = (double) megatonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) + { + double value = (double) milligramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) + { + double value = (double) milligramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) + { + double value = (double) milligramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); + } + /// + /// Get MassMomentOfInertia from MilligramSquareMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) + { + double value = (double) milligramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); + } + /// + /// Get MassMomentOfInertia from PoundSquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) + { + double value = (double) poundsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); + } + /// + /// Get MassMomentOfInertia from PoundSquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) + { + double value = (double) poundsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); + } + /// + /// Get MassMomentOfInertia from SlugSquareFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromSlugSquareFeet(double slugsquarefeet) + { + double value = (double) slugsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); + } + /// + /// Get MassMomentOfInertia from SlugSquareInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromSlugSquareInches(double slugsquareinches) + { + double value = (double) slugsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); + } + /// + /// Get MassMomentOfInertia from TonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) + { + double value = (double) tonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) + { + double value = (double) tonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) + { + double value = (double) tonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) + { + double value = (double) tonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// MassMomentOfInertia unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) + { + return new MassMomentOfInertia((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +651,393 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassMomentOfInertia Parse(string str, [CanBeNull] string cultureName) + public static MassMomentOfInertia Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassMomentOfInertiaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramSquareMeters(x.KilogramSquareMeters + y.KilogramSquareMeters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MassMomentOfInertia); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MassMomentOfInertiaUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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 - if (unit == MassMomentOfInertiaUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassMomentOfInertiaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . + /// + /// A MassMomentOfInertia with the specified unit. + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MassMomentOfInertia(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs index 2ce16e7f46..e52392f58c 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Molar energy is the amount of energy stored in 1 mole of a substance. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarEnergy + public sealed partial class MolarEnergy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEnergyUnit? _unit; + + static MolarEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerMole. /// @@ -75,28 +80,184 @@ public MolarEnergy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MolarEnergy(double numericValue, MolarEnergyUnit unit) + { + if(unit == MolarEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. + /// + public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; + + /// + /// Represents the largest possible value of MolarEnergy + /// + public static MolarEnergy MaxValue => new MolarEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarEnergy + /// + public static MolarEnergy MinValue => new MolarEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarEnergy; + + /// + /// All units of measurement for the MolarEnergy quantity. + /// + public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. + /// + public static MolarEnergy Zero => new MolarEnergy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MolarEnergy in JoulesPerMole. + /// + public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); + + /// + /// Get MolarEnergy in KilojoulesPerMole. + /// + public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); + + /// + /// Get MolarEnergy in MegajoulesPerMole. + /// + public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MolarEnergy from JoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromJoulesPerMole(double joulespermole) + { + double value = (double) joulespermole; + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); + } + /// + /// Get MolarEnergy from KilojoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) + { + double value = (double) kilojoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); + } + /// + /// Get MolarEnergy from MegajoulesPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) + { + double value = (double) megajoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// MolarEnergy unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) + { + return new MolarEnergy((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarEnergy Parse(string str, [CanBeNull] string cultureName) + public static MolarEnergy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerMole(x.JoulesPerMole + y.JoulesPerMole)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MolarEnergy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MolarEnergyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MolarEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out MolarEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == MolarEnergyUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MolarEnergy to another MolarEnergy with the unit representation . + /// + /// A MolarEnergy with the specified unit. + public MolarEnergy ToUnit(MolarEnergyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MolarEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MolarEnergyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs index 9884724641..8aeef88d13 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarEntropy + public sealed partial class MolarEntropy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEntropyUnit? _unit; + + static MolarEntropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerMoleKelvin. /// @@ -75,28 +80,184 @@ public MolarEntropy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MolarEntropy(double numericValue, MolarEntropyUnit unit) + { + if(unit == MolarEntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. + /// + public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; + + /// + /// Represents the largest possible value of MolarEntropy + /// + public static MolarEntropy MaxValue => new MolarEntropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarEntropy + /// + public static MolarEntropy MinValue => new MolarEntropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarEntropy; + + /// + /// All units of measurement for the MolarEntropy quantity. + /// + public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// + public static MolarEntropy Zero => new MolarEntropy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MolarEntropy in JoulesPerMoleKelvin. + /// + public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); + + /// + /// Get MolarEntropy in KilojoulesPerMoleKelvin. + /// + public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); + + /// + /// Get MolarEntropy in MegajoulesPerMoleKelvin. + /// + public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MolarEntropy from JoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) + { + double value = (double) joulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from KilojoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) + { + double value = (double) kilojoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from MegajoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) + { + double value = (double) megajoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// MolarEntropy unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) + { + return new MolarEntropy((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarEntropy Parse(string str, [CanBeNull] string cultureName) + public static MolarEntropy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarEntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerMoleKelvin(x.JoulesPerMoleKelvin + y.JoulesPerMoleKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MolarEntropy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MolarEntropyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MolarEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out MolarEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == MolarEntropyUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MolarEntropy to another MolarEntropy with the unit representation . + /// + /// A MolarEntropy with the specified unit. + public MolarEntropy ToUnit(MolarEntropyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MolarEntropy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MolarEntropyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs index cb4669e427..3c1d4158ed 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarMass + public sealed partial class MolarMass : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarMassUnit? _unit; + + static MolarMass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); + } /// /// Creates the quantity with a value of 0 in the base unit KilogramPerMole. /// @@ -75,28 +80,319 @@ public MolarMass() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private MolarMass(double numericValue, MolarMassUnit unit) + { + if(unit == MolarMassUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. + /// + public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; + + /// + /// Represents the largest possible value of MolarMass + /// + public static MolarMass MaxValue => new MolarMass(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarMass + /// + public static MolarMass MinValue => new MolarMass(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarMass; + + /// + /// All units of measurement for the MolarMass quantity. + /// + public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. + /// + public static MolarMass Zero => new MolarMass(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarMass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarMass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MolarMass in CentigramsPerMole. + /// + public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); + + /// + /// Get MolarMass in DecagramsPerMole. + /// + public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); + + /// + /// Get MolarMass in DecigramsPerMole. + /// + public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); + + /// + /// Get MolarMass in GramsPerMole. + /// + public double GramsPerMole => As(MolarMassUnit.GramPerMole); + + /// + /// Get MolarMass in HectogramsPerMole. + /// + public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); + + /// + /// Get MolarMass in KilogramsPerMole. + /// + public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); + + /// + /// Get MolarMass in KilopoundsPerMole. + /// + public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); + + /// + /// Get MolarMass in MegapoundsPerMole. + /// + public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); + + /// + /// Get MolarMass in MicrogramsPerMole. + /// + public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); + + /// + /// Get MolarMass in MilligramsPerMole. + /// + public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); + + /// + /// Get MolarMass in NanogramsPerMole. + /// + public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); + + /// + /// Get MolarMass in PoundsPerMole. + /// + public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get MolarMass from CentigramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromCentigramsPerMole(double centigramspermole) + { + double value = (double) centigramspermole; + return new MolarMass(value, MolarMassUnit.CentigramPerMole); + } + /// + /// Get MolarMass from DecagramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromDecagramsPerMole(double decagramspermole) + { + double value = (double) decagramspermole; + return new MolarMass(value, MolarMassUnit.DecagramPerMole); + } + /// + /// Get MolarMass from DecigramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromDecigramsPerMole(double decigramspermole) + { + double value = (double) decigramspermole; + return new MolarMass(value, MolarMassUnit.DecigramPerMole); + } + /// + /// Get MolarMass from GramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromGramsPerMole(double gramspermole) + { + double value = (double) gramspermole; + return new MolarMass(value, MolarMassUnit.GramPerMole); + } + /// + /// Get MolarMass from HectogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromHectogramsPerMole(double hectogramspermole) + { + double value = (double) hectogramspermole; + return new MolarMass(value, MolarMassUnit.HectogramPerMole); + } + /// + /// Get MolarMass from KilogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromKilogramsPerMole(double kilogramspermole) + { + double value = (double) kilogramspermole; + return new MolarMass(value, MolarMassUnit.KilogramPerMole); + } + /// + /// Get MolarMass from KilopoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) + { + double value = (double) kilopoundspermole; + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); + } + /// + /// Get MolarMass from MegapoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMegapoundsPerMole(double megapoundspermole) + { + double value = (double) megapoundspermole; + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); + } + /// + /// Get MolarMass from MicrogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMicrogramsPerMole(double microgramspermole) + { + double value = (double) microgramspermole; + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); + } + /// + /// Get MolarMass from MilligramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromMilligramsPerMole(double milligramspermole) + { + double value = (double) milligramspermole; + return new MolarMass(value, MolarMassUnit.MilligramPerMole); + } + /// + /// Get MolarMass from NanogramsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromNanogramsPerMole(double nanogramspermole) + { + double value = (double) nanogramspermole; + return new MolarMass(value, MolarMassUnit.NanogramPerMole); + } + /// + /// Get MolarMass from PoundsPerMole. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static MolarMass FromPoundsPerMole(double poundspermole) + { + double value = (double) poundspermole; + return new MolarMass(value, MolarMassUnit.PoundPerMole); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +411,361 @@ public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] string cult /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarMass Parse(string str, [CanBeNull] string cultureName) + public static MolarMass Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarMassUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerMole(x.KilogramsPerMole + y.KilogramsPerMole)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(MolarMass); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MolarMassUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MolarMassUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is MolarMass objMolarMass)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + return CompareTo(objMolarMass); + } - if (unit == MolarMassUnit.Undefined) + // Windows 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarMassUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this MolarMass to another MolarMass with the unit representation . + /// + /// A MolarMass with the specified unit. + public MolarMass ToUnit(MolarMassUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new MolarMass(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarMassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MolarMassUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs index 55ab72cfa5..f84d42c175 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Molarity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarityUnit? _unit; + static Molarity() + { + BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); + } /// /// Creates the quantity with a value of 0 in the base unit MolesPerCubicMeter. /// @@ -75,28 +83,259 @@ public Molarity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Molarity(double numericValue, MolarityUnit unit) + { + if(unit == MolarityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. + /// + public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; + + /// + /// Represents the largest possible value of Molarity + /// + public static Molarity MaxValue => new Molarity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Molarity + /// + public static Molarity MinValue => new Molarity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Molarity; + + /// + /// All units of measurement for the Molarity quantity. + /// + public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. + /// + public static Molarity Zero => new Molarity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Molarity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Molarity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Molarity in CentimolesPerLiter. + /// + public double CentimolesPerLiter => As(MolarityUnit.CentimolesPerLiter); + + /// + /// Get Molarity in DecimolesPerLiter. + /// + public double DecimolesPerLiter => As(MolarityUnit.DecimolesPerLiter); + + /// + /// Get Molarity in MicromolesPerLiter. + /// + public double MicromolesPerLiter => As(MolarityUnit.MicromolesPerLiter); + + /// + /// Get Molarity in MillimolesPerLiter. + /// + public double MillimolesPerLiter => As(MolarityUnit.MillimolesPerLiter); + + /// + /// Get Molarity in MolesPerCubicMeter. + /// + public double MolesPerCubicMeter => As(MolarityUnit.MolesPerCubicMeter); + + /// + /// Get Molarity in MolesPerLiter. + /// + public double MolesPerLiter => As(MolarityUnit.MolesPerLiter); + + /// + /// Get Molarity in NanomolesPerLiter. + /// + public double NanomolesPerLiter => As(MolarityUnit.NanomolesPerLiter); + + /// + /// Get Molarity in PicomolesPerLiter. + /// + public double PicomolesPerLiter => As(MolarityUnit.PicomolesPerLiter); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Molarity from CentimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromCentimolesPerLiter(double centimolesperliter) + { + double value = (double) centimolesperliter; + return new Molarity(value, MolarityUnit.CentimolesPerLiter); + } + /// + /// Get Molarity from DecimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromDecimolesPerLiter(double decimolesperliter) + { + double value = (double) decimolesperliter; + return new Molarity(value, MolarityUnit.DecimolesPerLiter); + } + /// + /// Get Molarity from MicromolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMicromolesPerLiter(double micromolesperliter) + { + double value = (double) micromolesperliter; + return new Molarity(value, MolarityUnit.MicromolesPerLiter); + } + /// + /// Get Molarity from MillimolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMillimolesPerLiter(double millimolesperliter) + { + double value = (double) millimolesperliter; + return new Molarity(value, MolarityUnit.MillimolesPerLiter); + } + /// + /// Get Molarity from MolesPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) + { + double value = (double) molespercubicmeter; + return new Molarity(value, MolarityUnit.MolesPerCubicMeter); + } + /// + /// Get Molarity from MolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromMolesPerLiter(double molesperliter) + { + double value = (double) molesperliter; + return new Molarity(value, MolarityUnit.MolesPerLiter); + } + /// + /// Get Molarity from NanomolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromNanomolesPerLiter(double nanomolesperliter) + { + double value = (double) nanomolesperliter; + return new Molarity(value, MolarityUnit.NanomolesPerLiter); + } + /// + /// Get Molarity from PicomolesPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Molarity FromPicomolesPerLiter(double picomolesperliter) + { + double value = (double) picomolesperliter; + return new Molarity(value, MolarityUnit.PicomolesPerLiter); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +354,353 @@ public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Molarity Parse(string str, [CanBeNull] string cultureName) + public static Molarity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMolesPerCubicMeter(x.MolesPerCubicMeter + y.MolesPerCubicMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Molarity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static MolarityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static MolarityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == MolarityUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return _value; + case MolarityUnit.MolesPerLiter: return _value/1e-3; + case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(MolarityUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; + case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; + case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(MolarityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs index 4da2995f20..2916a7cc26 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Permeability : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly PermeabilityUnit? _unit; + + static Permeability() + { + BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit HenryPerMeter. /// @@ -75,28 +83,154 @@ public Permeability() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Permeability(double numericValue, PermeabilityUnit unit) + { + if(unit == PermeabilityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. + /// + public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; + + /// + /// Represents the largest possible value of Permeability + /// + public static Permeability MaxValue => new Permeability(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Permeability + /// + public static Permeability MinValue => new Permeability(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Permeability; + + /// + /// All units of measurement for the Permeability quantity. + /// + public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. + /// + public static Permeability Zero => new Permeability(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permeability.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permeability in HenriesPerMeter. + /// + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermeabilityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permeability from HenriesPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Permeability FromHenriesPerMeter(double henriespermeter) + { + double value = (double) henriespermeter; + return new Permeability(value, PermeabilityUnit.HenryPerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Permeability Parse(string str, [CanBeNull] string cultureName) + public static Permeability Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PermeabilityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHenriesPerMeter(x.HenriesPerMeter + y.HenriesPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Permeability); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PermeabilityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermeabilityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == PermeabilityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermeabilityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PermeabilityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs index affe190eb0..8ddb1a058e 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class Permittivity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly PermittivityUnit? _unit; + + static Permittivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit FaradPerMeter. /// @@ -75,28 +83,154 @@ public Permittivity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Permittivity(double numericValue, PermittivityUnit unit) + { + if(unit == PermittivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. + /// + public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; + + /// + /// Represents the largest possible value of Permittivity + /// + public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Permittivity + /// + public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Permittivity; + + /// + /// All units of measurement for the Permittivity quantity. + /// + public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. + /// + public static Permittivity Zero => new Permittivity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permittivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permittivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permittivity in FaradsPerMeter. + /// + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermittivityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Permittivity from FaradsPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Permittivity FromFaradsPerMeter(double faradspermeter) + { + double value = (double) faradspermeter; + return new Permittivity(value, PermittivityUnit.FaradPerMeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Permittivity Parse(string str, [CanBeNull] string cultureName) + public static Permittivity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PermittivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromFaradsPerMeter(x.FaradsPerMeter + y.FaradsPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Permittivity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PermittivityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PermittivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermittivityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == PermittivityUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermittivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PermittivityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs index a59fa54f37..142abfee8c 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Power + public sealed partial class Power : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly decimal _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerUnit? _unit; + + static Power() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Watt. /// @@ -75,28 +80,439 @@ public Power() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Power(decimal numericValue, PowerUnit unit) + { + if(unit == PowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Power, which is Watt. All conversions go via this value. + /// + public static PowerUnit BaseUnit => PowerUnit.Watt; + + /// + /// Represents the largest possible value of Power + /// + public static Power MaxValue => new Power(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Power + /// + public static Power MinValue => new Power(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Power; + + /// + /// All units of measurement for the Power quantity. + /// + public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// + public static Power Zero => new Power(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Power.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Power.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Power in BoilerHorsepower. + /// + public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + + /// + /// Get Power in BritishThermalUnitsPerHour. + /// + public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + + /// + /// Get Power in Decawatts. + /// + public double Decawatts => As(PowerUnit.Decawatt); + + /// + /// Get Power in Deciwatts. + /// + public double Deciwatts => As(PowerUnit.Deciwatt); + + /// + /// Get Power in ElectricalHorsepower. + /// + public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + + /// + /// Get Power in Femtowatts. + /// + public double Femtowatts => As(PowerUnit.Femtowatt); + + /// + /// Get Power in Gigawatts. + /// + public double Gigawatts => As(PowerUnit.Gigawatt); + + /// + /// Get Power in HydraulicHorsepower. + /// + public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + + /// + /// Get Power in KilobritishThermalUnitsPerHour. + /// + public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + + /// + /// Get Power in Kilowatts. + /// + public double Kilowatts => As(PowerUnit.Kilowatt); + + /// + /// Get Power in MechanicalHorsepower. + /// + public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + + /// + /// Get Power in Megawatts. + /// + public double Megawatts => As(PowerUnit.Megawatt); + + /// + /// Get Power in MetricHorsepower. + /// + public double MetricHorsepower => As(PowerUnit.MetricHorsepower); + + /// + /// Get Power in Microwatts. + /// + public double Microwatts => As(PowerUnit.Microwatt); + + /// + /// Get Power in Milliwatts. + /// + public double Milliwatts => As(PowerUnit.Milliwatt); + + /// + /// Get Power in Nanowatts. + /// + public double Nanowatts => As(PowerUnit.Nanowatt); + + /// + /// Get Power in Petawatts. + /// + public double Petawatts => As(PowerUnit.Petawatt); + + /// + /// Get Power in Picowatts. + /// + public double Picowatts => As(PowerUnit.Picowatt); + + /// + /// Get Power in Terawatts. + /// + public double Terawatts => As(PowerUnit.Terawatt); + + /// + /// Get Power in Watts. + /// + public double Watts => As(PowerUnit.Watt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PowerUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get Power from BoilerHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromBoilerHorsepower(double boilerhorsepower) + { + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); + } + /// + /// Get Power from BritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) + { + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); + } + /// + /// Get Power from Decawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromDecawatts(double decawatts) + { + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); + } + /// + /// Get Power from Deciwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromDeciwatts(double deciwatts) + { + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); + } + /// + /// Get Power from ElectricalHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromElectricalHorsepower(double electricalhorsepower) + { + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); + } + /// + /// Get Power from Femtowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromFemtowatts(double femtowatts) + { + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); + } + /// + /// Get Power from Gigawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromGigawatts(double gigawatts) + { + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); + } + /// + /// Get Power from HydraulicHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromHydraulicHorsepower(double hydraulichorsepower) + { + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); + } + /// + /// Get Power from KilobritishThermalUnitsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) + { + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); + } + /// + /// Get Power from Kilowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromKilowatts(double kilowatts) + { + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); + } + /// + /// Get Power from MechanicalHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMechanicalHorsepower(double mechanicalhorsepower) + { + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); + } + /// + /// Get Power from Megawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMegawatts(double megawatts) + { + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); + } + /// + /// Get Power from MetricHorsepower. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMetricHorsepower(double metrichorsepower) + { + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); + } + /// + /// Get Power from Microwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMicrowatts(double microwatts) + { + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); + } + /// + /// Get Power from Milliwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromMilliwatts(double milliwatts) + { + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); + } + /// + /// Get Power from Nanowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromNanowatts(double nanowatts) + { + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); + } + /// + /// Get Power from Petawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromPetawatts(double petawatts) + { + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); + } + /// + /// Get Power from Picowatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromPicowatts(double picowatts) + { + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); + } + /// + /// Get Power from Terawatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromTerawatts(double terawatts) + { + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); + } + /// + /// Get Power from Watts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Power FromWatts(double watts) + { + decimal value = (decimal) watts; + return new Power(value, PowerUnit.Watt); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +531,377 @@ public static string GetAbbreviation(PowerUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Power Parse(string str, [CanBeNull] string cultureName) + public static Power Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWatts(x.Watts + y.Watts)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Power); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PowerUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #region Equality / IComparable - if (unit == PowerUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Power to another Power with the unit representation . + /// + /// A Power with the specified unit. + public Power ToUnit(PowerUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Power(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PowerUnit.BoilerHorsepower: return _value*9812.5m; + case PowerUnit.BritishThermalUnitPerHour: return _value*0.293071m; + case PowerUnit.Decawatt: return (_value) * 1e1m; + case PowerUnit.Deciwatt: return (_value) * 1e-1m; + case PowerUnit.ElectricalHorsepower: return _value*746m; + case PowerUnit.Femtowatt: return (_value) * 1e-15m; + case PowerUnit.Gigawatt: return (_value) * 1e9m; + case PowerUnit.HydraulicHorsepower: return _value*745.69988145m; + case PowerUnit.KilobritishThermalUnitPerHour: return (_value*0.293071m) * 1e3m; + case PowerUnit.Kilowatt: return (_value) * 1e3m; + case PowerUnit.MechanicalHorsepower: return _value*745.69m; + case PowerUnit.Megawatt: return (_value) * 1e6m; + case PowerUnit.MetricHorsepower: return _value*735.49875m; + case PowerUnit.Microwatt: return (_value) * 1e-6m; + case PowerUnit.Milliwatt: return (_value) * 1e-3m; + case PowerUnit.Nanowatt: return (_value) * 1e-9m; + case PowerUnit.Petawatt: return (_value) * 1e15m; + case PowerUnit.Picowatt: return (_value) * 1e-12m; + case PowerUnit.Terawatt: return (_value) * 1e12m; + case PowerUnit.Watt: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private decimal AsBaseNumericType(PowerUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case PowerUnit.BoilerHorsepower: return baseUnitValue/9812.5m; + case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue/0.293071m; + case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; + case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; + case PowerUnit.ElectricalHorsepower: return baseUnitValue/746m; + case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; + case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; + case PowerUnit.HydraulicHorsepower: return baseUnitValue/745.69988145m; + case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue/0.293071m) / 1e3m; + case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; + case PowerUnit.MechanicalHorsepower: return baseUnitValue/745.69m; + case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; + case PowerUnit.MetricHorsepower: return baseUnitValue/735.49875m; + case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; + case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; + case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; + case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; + case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; + case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; + case PowerUnit.Watt: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PowerUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs index b914aef018..47ea186351 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The amount of power in a volume. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PowerDensity + public sealed partial class PowerDensity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerDensityUnit? _unit; + static PowerDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit WattPerCubicMeter. /// @@ -75,28 +80,799 @@ public PowerDensity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private PowerDensity(double numericValue, PowerDensityUnit unit) + { + if(unit == PowerDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. + /// + public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; + + /// + /// Represents the largest possible value of PowerDensity + /// + public static PowerDensity MaxValue => new PowerDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of PowerDensity + /// + public static PowerDensity MinValue => new PowerDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PowerDensity; + + /// + /// All units of measurement for the PowerDensity quantity. + /// + public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. + /// + public static PowerDensity Zero => new PowerDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PowerDensity in DecawattsPerCubicFoot. + /// + public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); + + /// + /// Get PowerDensity in DecawattsPerCubicInch. + /// + public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); + + /// + /// Get PowerDensity in DecawattsPerCubicMeter. + /// + public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); + + /// + /// Get PowerDensity in DecawattsPerLiter. + /// + public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); + + /// + /// Get PowerDensity in DeciwattsPerCubicFoot. + /// + public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); + + /// + /// Get PowerDensity in DeciwattsPerCubicInch. + /// + public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); + + /// + /// Get PowerDensity in DeciwattsPerCubicMeter. + /// + public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); + + /// + /// Get PowerDensity in DeciwattsPerLiter. + /// + public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); + + /// + /// Get PowerDensity in GigawattsPerCubicFoot. + /// + public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); + + /// + /// Get PowerDensity in GigawattsPerCubicInch. + /// + public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); + + /// + /// Get PowerDensity in GigawattsPerCubicMeter. + /// + public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); + + /// + /// Get PowerDensity in GigawattsPerLiter. + /// + public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); + + /// + /// Get PowerDensity in KilowattsPerCubicFoot. + /// + public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); + + /// + /// Get PowerDensity in KilowattsPerCubicInch. + /// + public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); + + /// + /// Get PowerDensity in KilowattsPerCubicMeter. + /// + public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); + + /// + /// Get PowerDensity in KilowattsPerLiter. + /// + public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); + + /// + /// Get PowerDensity in MegawattsPerCubicFoot. + /// + public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); + + /// + /// Get PowerDensity in MegawattsPerCubicInch. + /// + public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); + + /// + /// Get PowerDensity in MegawattsPerCubicMeter. + /// + public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); + + /// + /// Get PowerDensity in MegawattsPerLiter. + /// + public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); + + /// + /// Get PowerDensity in MicrowattsPerCubicFoot. + /// + public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); + + /// + /// Get PowerDensity in MicrowattsPerCubicInch. + /// + public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); + + /// + /// Get PowerDensity in MicrowattsPerCubicMeter. + /// + public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); + + /// + /// Get PowerDensity in MicrowattsPerLiter. + /// + public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); + + /// + /// Get PowerDensity in MilliwattsPerCubicFoot. + /// + public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); + + /// + /// Get PowerDensity in MilliwattsPerCubicInch. + /// + public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); + + /// + /// Get PowerDensity in MilliwattsPerCubicMeter. + /// + public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); + + /// + /// Get PowerDensity in MilliwattsPerLiter. + /// + public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); + + /// + /// Get PowerDensity in NanowattsPerCubicFoot. + /// + public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); + + /// + /// Get PowerDensity in NanowattsPerCubicInch. + /// + public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); + + /// + /// Get PowerDensity in NanowattsPerCubicMeter. + /// + public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); + + /// + /// Get PowerDensity in NanowattsPerLiter. + /// + public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); + + /// + /// Get PowerDensity in PicowattsPerCubicFoot. + /// + public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); + + /// + /// Get PowerDensity in PicowattsPerCubicInch. + /// + public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); + + /// + /// Get PowerDensity in PicowattsPerCubicMeter. + /// + public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); + + /// + /// Get PowerDensity in PicowattsPerLiter. + /// + public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); + + /// + /// Get PowerDensity in TerawattsPerCubicFoot. + /// + public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); + + /// + /// Get PowerDensity in TerawattsPerCubicInch. + /// + public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); + + /// + /// Get PowerDensity in TerawattsPerCubicMeter. + /// + public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); + + /// + /// Get PowerDensity in TerawattsPerLiter. + /// + public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); + + /// + /// Get PowerDensity in WattsPerCubicFoot. + /// + public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); + + /// + /// Get PowerDensity in WattsPerCubicInch. + /// + public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); + + /// + /// Get PowerDensity in WattsPerCubicMeter. + /// + public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); + + /// + /// Get PowerDensity in WattsPerLiter. + /// + public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get PowerDensity from DecawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) + { + double value = (double) decawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); + } + /// + /// Get PowerDensity from DecawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) + { + double value = (double) decawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); + } + /// + /// Get PowerDensity from DecawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) + { + double value = (double) decawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); + } + /// + /// Get PowerDensity from DecawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) + { + double value = (double) decawattsperliter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); + } + /// + /// Get PowerDensity from DeciwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) + { + double value = (double) deciwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); + } + /// + /// Get PowerDensity from DeciwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) + { + double value = (double) deciwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); + } + /// + /// Get PowerDensity from DeciwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) + { + double value = (double) deciwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); + } + /// + /// Get PowerDensity from DeciwattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) + { + double value = (double) deciwattsperliter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); } + /// + /// Get PowerDensity from GigawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) + { + double value = (double) gigawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); + } + /// + /// Get PowerDensity from GigawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) + { + double value = (double) gigawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); + } + /// + /// Get PowerDensity from GigawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) + { + double value = (double) gigawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); + } + /// + /// Get PowerDensity from GigawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) + { + double value = (double) gigawattsperliter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); + } + /// + /// Get PowerDensity from KilowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) + { + double value = (double) kilowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); + } + /// + /// Get PowerDensity from KilowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) + { + double value = (double) kilowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); + } + /// + /// Get PowerDensity from KilowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) + { + double value = (double) kilowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); + } + /// + /// Get PowerDensity from KilowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) + { + double value = (double) kilowattsperliter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); + } + /// + /// Get PowerDensity from MegawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) + { + double value = (double) megawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); + } + /// + /// Get PowerDensity from MegawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) + { + double value = (double) megawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); + } + /// + /// Get PowerDensity from MegawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) + { + double value = (double) megawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); + } + /// + /// Get PowerDensity from MegawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) + { + double value = (double) megawattsperliter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); + } + /// + /// Get PowerDensity from MicrowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) + { + double value = (double) microwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); + } + /// + /// Get PowerDensity from MicrowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) + { + double value = (double) microwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); + } + /// + /// Get PowerDensity from MicrowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) + { + double value = (double) microwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); + } + /// + /// Get PowerDensity from MicrowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) + { + double value = (double) microwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); + } + /// + /// Get PowerDensity from MilliwattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) + { + double value = (double) milliwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); + } + /// + /// Get PowerDensity from MilliwattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) + { + double value = (double) milliwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); + } + /// + /// Get PowerDensity from MilliwattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) + { + double value = (double) milliwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); + } + /// + /// Get PowerDensity from MilliwattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) + { + double value = (double) milliwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); + } + /// + /// Get PowerDensity from NanowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) + { + double value = (double) nanowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); + } + /// + /// Get PowerDensity from NanowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) + { + double value = (double) nanowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); + } + /// + /// Get PowerDensity from NanowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) + { + double value = (double) nanowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); + } + /// + /// Get PowerDensity from NanowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) + { + double value = (double) nanowattsperliter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); + } + /// + /// Get PowerDensity from PicowattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) + { + double value = (double) picowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); + } + /// + /// Get PowerDensity from PicowattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) + { + double value = (double) picowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); + } + /// + /// Get PowerDensity from PicowattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) + { + double value = (double) picowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); + } + /// + /// Get PowerDensity from PicowattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) + { + double value = (double) picowattsperliter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); + } + /// + /// Get PowerDensity from TerawattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) + { + double value = (double) terawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); + } + /// + /// Get PowerDensity from TerawattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) + { + double value = (double) terawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); + } + /// + /// Get PowerDensity from TerawattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) + { + double value = (double) terawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); + } + /// + /// Get PowerDensity from TerawattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) + { + double value = (double) terawattsperliter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); + } + /// + /// Get PowerDensity from WattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) + { + double value = (double) wattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); + } + /// + /// Get PowerDensity from WattsPerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) + { + double value = (double) wattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); + } + /// + /// Get PowerDensity from WattsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) + { + double value = (double) wattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); + } + /// + /// Get PowerDensity from WattsPerLiter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerDensity FromWattsPerLiter(double wattsperliter) + { + double value = (double) wattsperliter; + return new PowerDensity(value, PowerDensityUnit.WattPerLiter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// PowerDensity unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static PowerDensity From(double value, PowerDensityUnit fromUnit) + { + return new PowerDensity((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +891,425 @@ public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] string c /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static PowerDensity Parse(string str, [CanBeNull] string cultureName) + public static PowerDensity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerCubicMeter(x.WattsPerCubicMeter + y.WattsPerCubicMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(PowerDensity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PowerDensityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PowerDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// Parse a unit string. + /// + /// String to 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); + } - if (unit == PowerDensityUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this PowerDensity to another PowerDensity with the unit representation . + /// + /// A PowerDensity with the specified unit. + public PowerDensity ToUnit(PowerDensityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new PowerDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PowerDensityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerDensityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerDensityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs index 568003e2d4..e603267b0e 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The strength of a signal expressed in decibels (dB) relative to one watt. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PowerRatio + public sealed partial class PowerRatio : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerRatioUnit? _unit; + + static PowerRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit DecibelWatt. /// @@ -75,28 +80,169 @@ public PowerRatio() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private PowerRatio(double numericValue, PowerRatioUnit unit) + { + if(unit == PowerRatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. + /// + public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; + + /// + /// Represents the largest possible value of PowerRatio + /// + public static PowerRatio MaxValue => new PowerRatio(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of PowerRatio + /// + public static PowerRatio MinValue => new PowerRatio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PowerRatio; + + /// + /// All units of measurement for the PowerRatio quantity. + /// + public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. + /// + public static PowerRatio Zero => new PowerRatio(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PowerRatio in DecibelMilliwatts. + /// + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + + /// + /// Get PowerRatio in DecibelWatts. + /// + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerRatioUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerRatio from DecibelMilliwatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) + { + double value = (double) decibelmilliwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); + } + /// + /// Get PowerRatio from DecibelWatts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PowerRatio FromDecibelWatts(double decibelwatts) + { + double value = (double) decibelwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelWatt); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] string cul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static PowerRatio Parse(string str, [CanBeNull] string cultureName) + public static PowerRatio Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerRatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibelWatts(x.DecibelWatts + y.DecibelWatts)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(PowerRatio); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PowerRatioUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PowerRatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == PowerRatioUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerRatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this PowerRatio to another PowerRatio with the unit representation . + /// + /// A PowerRatio with the specified unit. + public PowerRatio ToUnit(PowerRatioUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new PowerRatio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PowerRatioUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs index 47af2646de..147c74f916 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Pressure + public sealed partial class Pressure : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureUnit? _unit; + static Pressure() + { + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Pascal. /// @@ -75,28 +80,754 @@ public Pressure() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Pressure(double numericValue, PressureUnit unit) + { + if(unit == PressureUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Pressure, which is Pascal. All conversions go via this value. + /// + public static PressureUnit BaseUnit => PressureUnit.Pascal; + + /// + /// Represents the largest possible value of Pressure + /// + public static Pressure MaxValue => new Pressure(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Pressure + /// + public static Pressure MinValue => new Pressure(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Pressure; + + /// + /// All units of measurement for the Pressure quantity. + /// + public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. + /// + public static Pressure Zero => new Pressure(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Pressure.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Pressure.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Pressure in Atmospheres. + /// + public double Atmospheres => As(PressureUnit.Atmosphere); + + /// + /// Get Pressure in Bars. + /// + public double Bars => As(PressureUnit.Bar); + + /// + /// Get Pressure in Centibars. + /// + public double Centibars => As(PressureUnit.Centibar); + + /// + /// Get Pressure in Decapascals. + /// + public double Decapascals => As(PressureUnit.Decapascal); + + /// + /// Get Pressure in Decibars. + /// + public double Decibars => As(PressureUnit.Decibar); + + /// + /// Get Pressure in DynesPerSquareCentimeter. + /// + public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + + /// + /// Get Pressure in FeetOfHead. + /// + public double FeetOfHead => As(PressureUnit.FootOfHead); + + /// + /// Get Pressure in Gigapascals. + /// + public double Gigapascals => As(PressureUnit.Gigapascal); + + /// + /// Get Pressure in Hectopascals. + /// + public double Hectopascals => As(PressureUnit.Hectopascal); + + /// + /// Get Pressure in InchesOfMercury. + /// + public double InchesOfMercury => As(PressureUnit.InchOfMercury); + + /// + /// Get Pressure in Kilobars. + /// + public double Kilobars => As(PressureUnit.Kilobar); + + /// + /// Get Pressure in KilogramsForcePerSquareCentimeter. + /// + public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); + + /// + /// Get Pressure in KilogramsForcePerSquareMeter. + /// + public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); + + /// + /// Get Pressure in KilogramsForcePerSquareMillimeter. + /// + public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); + + /// + /// Get Pressure in KilonewtonsPerSquareCentimeter. + /// + public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); + + /// + /// Get Pressure in KilonewtonsPerSquareMeter. + /// + public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); + + /// + /// Get Pressure in KilonewtonsPerSquareMillimeter. + /// + public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); + + /// + /// Get Pressure in Kilopascals. + /// + public double Kilopascals => As(PressureUnit.Kilopascal); + + /// + /// Get Pressure in KilopoundsForcePerSquareFoot. + /// + public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); + + /// + /// Get Pressure in KilopoundsForcePerSquareInch. + /// + public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); + + /// + /// Get Pressure in Megabars. + /// + public double Megabars => As(PressureUnit.Megabar); + + /// + /// Get Pressure in MeganewtonsPerSquareMeter. + /// + public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); + + /// + /// Get Pressure in Megapascals. + /// + public double Megapascals => As(PressureUnit.Megapascal); + + /// + /// Get Pressure in MetersOfHead. + /// + public double MetersOfHead => As(PressureUnit.MeterOfHead); + + /// + /// Get Pressure in Microbars. + /// + public double Microbars => As(PressureUnit.Microbar); + + /// + /// Get Pressure in Micropascals. + /// + public double Micropascals => As(PressureUnit.Micropascal); + + /// + /// Get Pressure in Millibars. + /// + public double Millibars => As(PressureUnit.Millibar); + + /// + /// Get Pressure in MillimetersOfMercury. + /// + public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); + + /// + /// Get Pressure in Millipascals. + /// + public double Millipascals => As(PressureUnit.Millipascal); + + /// + /// Get Pressure in NewtonsPerSquareCentimeter. + /// + public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); + + /// + /// Get Pressure in NewtonsPerSquareMeter. + /// + public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); + + /// + /// Get Pressure in NewtonsPerSquareMillimeter. + /// + public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); + + /// + /// Get Pressure in Pascals. + /// + public double Pascals => As(PressureUnit.Pascal); + + /// + /// Get Pressure in PoundsForcePerSquareFoot. + /// + public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); + + /// + /// Get Pressure in PoundsForcePerSquareInch. + /// + public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); + + /// + /// Get Pressure in PoundsPerInchSecondSquared. + /// + public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + + /// + /// Get Pressure in TechnicalAtmospheres. + /// + public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); + + /// + /// Get Pressure in TonnesForcePerSquareCentimeter. + /// + public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); + + /// + /// Get Pressure in TonnesForcePerSquareMeter. + /// + public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); + + /// + /// Get Pressure in TonnesForcePerSquareMillimeter. + /// + public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); + + /// + /// Get Pressure in Torrs. + /// + public double Torrs => As(PressureUnit.Torr); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(PressureUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Pressure from Atmospheres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromAtmospheres(double atmospheres) + { + double value = (double) atmospheres; + return new Pressure(value, PressureUnit.Atmosphere); + } + /// + /// Get Pressure from Bars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromBars(double bars) + { + double value = (double) bars; + return new Pressure(value, PressureUnit.Bar); + } + /// + /// Get Pressure from Centibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromCentibars(double centibars) + { + double value = (double) centibars; + return new Pressure(value, PressureUnit.Centibar); + } + /// + /// Get Pressure from Decapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDecapascals(double decapascals) + { + double value = (double) decapascals; + return new Pressure(value, PressureUnit.Decapascal); + } + /// + /// Get Pressure from Decibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDecibars(double decibars) + { + double value = (double) decibars; + return new Pressure(value, PressureUnit.Decibar); + } + /// + /// Get Pressure from DynesPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromDynesPerSquareCentimeter(double dynespersquarecentimeter) + { + double value = (double) dynespersquarecentimeter; + return new Pressure(value, PressureUnit.DynePerSquareCentimeter); + } + /// + /// Get Pressure from FeetOfHead. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromFeetOfHead(double feetofhead) + { + double value = (double) feetofhead; + return new Pressure(value, PressureUnit.FootOfHead); + } + /// + /// Get Pressure from Gigapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromGigapascals(double gigapascals) + { + double value = (double) gigapascals; + return new Pressure(value, PressureUnit.Gigapascal); + } + /// + /// Get Pressure from Hectopascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromHectopascals(double hectopascals) + { + double value = (double) hectopascals; + return new Pressure(value, PressureUnit.Hectopascal); + } + /// + /// Get Pressure from InchesOfMercury. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromInchesOfMercury(double inchesofmercury) + { + double value = (double) inchesofmercury; + return new Pressure(value, PressureUnit.InchOfMercury); + } + /// + /// Get Pressure from Kilobars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilobars(double kilobars) + { + double value = (double) kilobars; + return new Pressure(value, PressureUnit.Kilobar); + } + /// + /// Get Pressure from KilogramsForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) + { + double value = (double) kilogramsforcepersquarecentimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) + { + double value = (double) kilogramsforcepersquaremeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); + } + /// + /// Get Pressure from KilogramsForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) + { + double value = (double) kilogramsforcepersquaremillimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) + { + double value = (double) kilonewtonspersquarecentimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) + { + double value = (double) kilonewtonspersquaremeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); + } + /// + /// Get Pressure from KilonewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) + { + double value = (double) kilonewtonspersquaremillimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Kilopascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopascals(double kilopascals) + { + double value = (double) kilopascals; + return new Pressure(value, PressureUnit.Kilopascal); + } + /// + /// Get Pressure from KilopoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) + { + double value = (double) kilopoundsforcepersquarefoot; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); + } + /// + /// Get Pressure from KilopoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) + { + double value = (double) kilopoundsforcepersquareinch; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); + } + /// + /// Get Pressure from Megabars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMegabars(double megabars) + { + double value = (double) megabars; + return new Pressure(value, PressureUnit.Megabar); + } + /// + /// Get Pressure from MeganewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMeganewtonsPerSquareMeter(double meganewtonspersquaremeter) + { + double value = (double) meganewtonspersquaremeter; + return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); + } + /// + /// Get Pressure from Megapascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMegapascals(double megapascals) + { + double value = (double) megapascals; + return new Pressure(value, PressureUnit.Megapascal); + } + /// + /// Get Pressure from MetersOfHead. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMetersOfHead(double metersofhead) + { + double value = (double) metersofhead; + return new Pressure(value, PressureUnit.MeterOfHead); + } + /// + /// Get Pressure from Microbars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMicrobars(double microbars) + { + double value = (double) microbars; + return new Pressure(value, PressureUnit.Microbar); + } + /// + /// Get Pressure from Micropascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMicropascals(double micropascals) + { + double value = (double) micropascals; + return new Pressure(value, PressureUnit.Micropascal); + } + /// + /// Get Pressure from Millibars. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMillibars(double millibars) + { + double value = (double) millibars; + return new Pressure(value, PressureUnit.Millibar); + } + /// + /// Get Pressure from MillimetersOfMercury. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromMillimetersOfMercury(double millimetersofmercury) + { + double value = (double) millimetersofmercury; + return new Pressure(value, PressureUnit.MillimeterOfMercury); + } + /// + /// Get Pressure from Millipascals. + /// + /// 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); + } + /// + /// Get Pressure from NewtonsPerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) + { + double value = (double) newtonspersquarecentimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); + } + /// + /// Get Pressure from NewtonsPerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) + { + double value = (double) newtonspersquaremeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); + } + /// + /// Get Pressure from NewtonsPerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) + { + double value = (double) newtonspersquaremillimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); + } + /// + /// Get Pressure from Pascals. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPascals(double pascals) + { + double value = (double) pascals; + return new Pressure(value, PressureUnit.Pascal); + } + /// + /// Get Pressure from PoundsForcePerSquareFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) + { + double value = (double) poundsforcepersquarefoot; + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); + } + /// + /// Get Pressure from PoundsForcePerSquareInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) + { + double value = (double) poundsforcepersquareinch; + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); + } + /// + /// Get Pressure from PoundsPerInchSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromPoundsPerInchSecondSquared(double poundsperinchsecondsquared) + { + double value = (double) poundsperinchsecondsquared; + return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); + } + /// + /// Get Pressure from TechnicalAtmospheres. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) + { + double value = (double) technicalatmospheres; + return new Pressure(value, PressureUnit.TechnicalAtmosphere); + } + /// + /// Get Pressure from TonnesForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) + { + double value = (double) tonnesforcepersquarecentimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) + { + double value = (double) tonnesforcepersquaremeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) + { + double value = (double) tonnesforcepersquaremillimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); + } + /// + /// Get Pressure from Torrs. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Pressure FromTorrs(double torrs) + { + double value = (double) torrs; + return new Pressure(value, PressureUnit.Torr); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +846,419 @@ public static string GetAbbreviation(PressureUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Pressure Parse(string str, [CanBeNull] string cultureName) + public static Pressure Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PressureUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromPascals(x.Pascals + y.Pascals)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Pressure); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PressureUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PressureUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == PressureUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PressureUnit.Atmosphere: return _value*1.01325*1e5; + case PressureUnit.Bar: return _value*1e5; + case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; + case PressureUnit.Decapascal: return (_value) * 1e1d; + case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; + case PressureUnit.DynePerSquareCentimeter: return _value*1.0e-1; + case PressureUnit.FootOfHead: return _value*2989.0669; + case PressureUnit.Gigapascal: return (_value) * 1e9d; + case PressureUnit.Hectopascal: return (_value) * 1e2d; + case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; + case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665e4; + case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; + case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9.80665e6; + case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; + case PressureUnit.Kilopascal: return (_value) * 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (_value*4.788025898033584e1) * 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (_value*6.894757293168361e3) * 1e3d; + case PressureUnit.Megabar: return (_value*1e5) * 1e6d; + case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; + case PressureUnit.Megapascal: return (_value) * 1e6d; + case PressureUnit.MeterOfHead: return _value*9804.139432; + case PressureUnit.Microbar: return (_value*1e5) * 1e-6d; + case PressureUnit.Micropascal: return (_value) * 1e-6d; + case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; + case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; + case PressureUnit.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.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(); - return unit; + switch(unit) + { + case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); + case PressureUnit.Bar: return baseUnitValue/1e5; + case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; + case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; + case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; + case PressureUnit.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; + case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; + case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; + case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; + case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; + case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/9.80665e4; + case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; + case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue/9.80665e6; + case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; + case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue/4.788025898033584e1) / 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue/6.894757293168361e3) / 1e3d; + case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; + case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; + case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; + case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; + case PressureUnit.Microbar: return (baseUnitValue/1e5) / 1e-6d; + case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; + case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; + case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; + case PressureUnit.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.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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PressureUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs index 0dde9096ad..50ac7e13a5 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PressureChangeRate + public sealed partial class PressureChangeRate : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureChangeRateUnit? _unit; + + static PressureChangeRate() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit PascalPerSecond. /// @@ -75,28 +80,199 @@ public PressureChangeRate() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private PressureChangeRate(double numericValue, PressureChangeRateUnit unit) + { + if(unit == PressureChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. + /// + public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; + + /// + /// Represents the largest possible value of PressureChangeRate + /// + public static PressureChangeRate MaxValue => new PressureChangeRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of PressureChangeRate + /// + public static PressureChangeRate MinValue => new PressureChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PressureChangeRate; + + /// + /// All units of measurement for the PressureChangeRate quantity. + /// + public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. + /// + public static PressureChangeRate Zero => new PressureChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PressureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PressureChangeRate in AtmospheresPerSecond. + /// + public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); + + /// + /// Get PressureChangeRate in KilopascalsPerSecond. + /// + public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); + + /// + /// Get PressureChangeRate in MegapascalsPerSecond. + /// + public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); + + /// + /// Get PressureChangeRate in PascalsPerSecond. + /// + public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get PressureChangeRate from AtmospheresPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) + { + double value = (double) atmospherespersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); + } + /// + /// Get PressureChangeRate from KilopascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) + { + double value = (double) kilopascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); + } + /// + /// Get PressureChangeRate from MegapascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) + { + double value = (double) megapascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); + } + /// + /// Get PressureChangeRate from PascalsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) + { + double value = (double) pascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +291,345 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] st /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static PressureChangeRate Parse(string str, [CanBeNull] string cultureName) + public static PressureChangeRate Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PressureChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromPascalsPerSecond(x.PascalsPerSecond + y.PascalsPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(PressureChangeRate); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static PressureChangeRateUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static PressureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == PressureChangeRateUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . + /// + /// A PressureChangeRate with the specified unit. + public PressureChangeRate ToUnit(PressureChangeRateUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new PressureChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; + case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(PressureChangeRateUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); + case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(PressureChangeRateUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs index b20e662734..8eb8809246 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Ratio + public sealed partial class Ratio : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RatioUnit? _unit; + static Ratio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit DecimalFraction. /// @@ -75,28 +80,229 @@ public Ratio() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Ratio(double numericValue, RatioUnit unit) + { + if(unit == RatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. + /// + public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; + + /// + /// Represents the largest possible value of Ratio + /// + public static Ratio MaxValue => new Ratio(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Ratio + /// + public static Ratio MinValue => new Ratio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Ratio; + + /// + /// All units of measurement for the Ratio quantity. + /// + public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// + public static Ratio Zero => new Ratio(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Ratio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Ratio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Ratio in DecimalFractions. + /// + public double DecimalFractions => As(RatioUnit.DecimalFraction); + + /// + /// Get Ratio in PartsPerBillion. + /// + public double PartsPerBillion => As(RatioUnit.PartPerBillion); + + /// + /// Get Ratio in PartsPerMillion. + /// + public double PartsPerMillion => As(RatioUnit.PartPerMillion); + + /// + /// Get Ratio in PartsPerThousand. + /// + public double PartsPerThousand => As(RatioUnit.PartPerThousand); + + /// + /// Get Ratio in PartsPerTrillion. + /// + public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); + + /// + /// Get Ratio in Percent. + /// + public double Percent => As(RatioUnit.Percent); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RatioUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(RatioUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get Ratio from DecimalFractions. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromDecimalFractions(double decimalfractions) + { + double value = (double) decimalfractions; + return new Ratio(value, RatioUnit.DecimalFraction); + } + /// + /// Get Ratio from PartsPerBillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerBillion(double partsperbillion) + { + double value = (double) partsperbillion; + return new Ratio(value, RatioUnit.PartPerBillion); } + /// + /// Get Ratio from PartsPerMillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerMillion(double partspermillion) + { + double value = (double) partspermillion; + return new Ratio(value, RatioUnit.PartPerMillion); + } + /// + /// Get Ratio from PartsPerThousand. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerThousand(double partsperthousand) + { + double value = (double) partsperthousand; + return new Ratio(value, RatioUnit.PartPerThousand); + } + /// + /// Get Ratio from PartsPerTrillion. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPartsPerTrillion(double partspertrillion) + { + double value = (double) partspertrillion; + return new Ratio(value, RatioUnit.PartPerTrillion); + } + /// + /// Get Ratio from Percent. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Ratio FromPercent(double percent) + { + double value = (double) percent; + return new Ratio(value, RatioUnit.Percent); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Ratio unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Ratio From(double value, RatioUnit fromUnit) + { + return new Ratio((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +321,349 @@ public static string GetAbbreviation(RatioUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Ratio Parse(string str, [CanBeNull] string cultureName) + public static Ratio Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecimalFractions(x.DecimalFractions + y.DecimalFractions)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Ratio); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static RatioUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static RatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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); + } - if (unit == RatioUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Ratio to another Ratio with the unit representation . + /// + /// A Ratio with the specified unit. + public Ratio ToUnit(RatioUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Ratio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(RatioUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs index 5264152de7..4416fafce4 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReactiveEnergy + public sealed partial class ReactiveEnergy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactiveEnergyUnit? _unit; + + static ReactiveEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit VoltampereReactiveHour. /// @@ -75,28 +80,184 @@ public ReactiveEnergy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ReactiveEnergy(double numericValue, ReactiveEnergyUnit unit) + { + if(unit == ReactiveEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. + /// + public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; + + /// + /// Represents the largest possible value of ReactiveEnergy + /// + public static ReactiveEnergy MaxValue => new ReactiveEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ReactiveEnergy + /// + public static ReactiveEnergy MinValue => new ReactiveEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ReactiveEnergy; + + /// + /// All units of measurement for the ReactiveEnergy quantity. + /// + public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// + public static ReactiveEnergy Zero => new ReactiveEnergy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactiveEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ReactiveEnergy in KilovoltampereReactiveHours. + /// + public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); + + /// + /// Get ReactiveEnergy in MegavoltampereReactiveHours. + /// + public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); + + /// + /// Get ReactiveEnergy in VoltampereReactiveHours. + /// + public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ReactiveEnergy from KilovoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) + { + double value = (double) kilovoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from MegavoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) + { + double value = (double) megavoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from VoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) + { + double value = (double) voltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ReactiveEnergy unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) + { + return new ReactiveEnergy((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ReactiveEnergy Parse(string str, [CanBeNull] string cultureName) + public static ReactiveEnergy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ReactiveEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltampereReactiveHours(x.VoltampereReactiveHours + y.VoltampereReactiveHours)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ReactiveEnergy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ReactiveEnergyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == ReactiveEnergyUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactiveEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . + /// + /// A ReactiveEnergy with the specified unit. + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ReactiveEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactiveEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs index 52599537a8..586c4fba33 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReactivePower + public sealed partial class ReactivePower : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactivePowerUnit? _unit; + + static ReactivePower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit VoltampereReactive. /// @@ -75,28 +80,199 @@ public ReactivePower() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ReactivePower(double numericValue, ReactivePowerUnit unit) + { + if(unit == ReactivePowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. + /// + public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; + + /// + /// Represents the largest possible value of ReactivePower + /// + public static ReactivePower MaxValue => new ReactivePower(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ReactivePower + /// + public static ReactivePower MinValue => new ReactivePower(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ReactivePower; + + /// + /// All units of measurement for the ReactivePower quantity. + /// + public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. + /// + public static ReactivePower Zero => new ReactivePower(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactivePower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactivePower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ReactivePower in GigavoltamperesReactive. + /// + public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); + + /// + /// Get ReactivePower in KilovoltamperesReactive. + /// + public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); + + /// + /// Get ReactivePower in MegavoltamperesReactive. + /// + public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); + + /// + /// Get ReactivePower in VoltamperesReactive. + /// + public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get ReactivePower from GigavoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) + { + double value = (double) gigavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); + } + /// + /// Get ReactivePower from KilovoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) + { + double value = (double) kilovoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); + } + /// + /// Get ReactivePower from MegavoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) + { + double value = (double) megavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); + } + /// + /// Get ReactivePower from VoltamperesReactive. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) + { + double value = (double) voltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +291,345 @@ public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ReactivePower Parse(string str, [CanBeNull] string cultureName) + public static ReactivePower Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ReactivePowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltamperesReactive(x.VoltamperesReactive + y.VoltamperesReactive)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ReactivePower); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ReactivePowerUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ReactivePowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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() { - if (str == null) throw new ArgumentNullException(nameof(str)); + return new { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion - if (unit == ReactivePowerUnit.Undefined) + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactivePowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ReactivePower to another ReactivePower with the unit representation . + /// + /// A ReactivePower with the specified unit. + public ReactivePower ToUnit(ReactivePowerUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ReactivePower(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactivePowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ReactivePowerUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs index 8b3430abee..f8b24a5ec0 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Angular acceleration is the rate of change of rotational speed. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalAcceleration + public sealed partial class RotationalAcceleration : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalAccelerationUnit? _unit; + + static RotationalAcceleration() + { + BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit RadianPerSecondSquared. /// @@ -75,28 +80,184 @@ public RotationalAcceleration() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private RotationalAcceleration(double numericValue, RotationalAccelerationUnit unit) + { + if(unit == RotationalAccelerationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. + /// + public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; + + /// + /// Represents the largest possible value of RotationalAcceleration + /// + public static RotationalAcceleration MaxValue => new RotationalAcceleration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalAcceleration + /// + public static RotationalAcceleration MinValue => new RotationalAcceleration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalAcceleration; + + /// + /// All units of measurement for the RotationalAcceleration quantity. + /// + public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// + public static RotationalAcceleration Zero => new RotationalAcceleration(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalAcceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get RotationalAcceleration in DegreesPerSecondSquared. + /// + public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); + + /// + /// Get RotationalAcceleration in RadiansPerSecondSquared. + /// + public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); + + /// + /// Get RotationalAcceleration in RevolutionsPerMinutePerSecond. + /// + public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get RotationalAcceleration from DegreesPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) + { + double value = (double) degreespersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); + } + /// + /// Get RotationalAcceleration from RadiansPerSecondSquared. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) + { + double value = (double) radianspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); + } + /// + /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) + { + double value = (double) revolutionsperminutepersecond; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// RotationalAcceleration unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) + { + return new RotationalAcceleration((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalAcceleration Parse(string str, [CanBeNull] string cultureName) + public static RotationalAcceleration Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalAccelerationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromRadiansPerSecondSquared(x.RadiansPerSecondSquared + y.RadiansPerSecondSquared)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(RotationalAcceleration); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static RotationalAccelerationUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == RotationalAccelerationUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalAccelerationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . + /// + /// A RotationalAcceleration with the specified unit. + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new RotationalAcceleration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalAccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; + case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(RotationalAccelerationUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; + case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs index 48fdd0b7bb..9a2c78e98a 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalSpeed + public sealed partial class RotationalSpeed : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalSpeedUnit? _unit; + + static RotationalSpeed() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit RadianPerSecond. /// @@ -75,28 +80,334 @@ public RotationalSpeed() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private RotationalSpeed(double numericValue, RotationalSpeedUnit unit) + { + if(unit == RotationalSpeedUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. + /// + public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; + + /// + /// Represents the largest possible value of RotationalSpeed + /// + public static RotationalSpeed MaxValue => new RotationalSpeed(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalSpeed + /// + public static RotationalSpeed MinValue => new RotationalSpeed(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalSpeed; + + /// + /// All units of measurement for the RotationalSpeed quantity. + /// + public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. + /// + public static RotationalSpeed Zero => new RotationalSpeed(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalSpeed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get RotationalSpeed in CentiradiansPerSecond. + /// + public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); + + /// + /// Get RotationalSpeed in DeciradiansPerSecond. + /// + public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); + + /// + /// Get RotationalSpeed in DegreesPerMinute. + /// + public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); + + /// + /// Get RotationalSpeed in DegreesPerSecond. + /// + public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); + + /// + /// Get RotationalSpeed in MicrodegreesPerSecond. + /// + public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); + + /// + /// Get RotationalSpeed in MicroradiansPerSecond. + /// + public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); + + /// + /// Get RotationalSpeed in MillidegreesPerSecond. + /// + public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); + + /// + /// Get RotationalSpeed in MilliradiansPerSecond. + /// + public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); + + /// + /// Get RotationalSpeed in NanodegreesPerSecond. + /// + public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); + + /// + /// Get RotationalSpeed in NanoradiansPerSecond. + /// + public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); + + /// + /// Get RotationalSpeed in RadiansPerSecond. + /// + public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); + + /// + /// Get RotationalSpeed in RevolutionsPerMinute. + /// + public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); + + /// + /// Get RotationalSpeed in RevolutionsPerSecond. + /// + public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalSpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalSpeed from CentiradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) + { + double value = (double) centiradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); + } + /// + /// Get RotationalSpeed from DeciradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) + { + double value = (double) deciradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); + } + /// + /// Get RotationalSpeed from DegreesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) + { + double value = (double) degreesperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); + } + /// + /// Get RotationalSpeed from DegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) + { + double value = (double) degreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); + } + /// + /// Get RotationalSpeed from MicrodegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) + { + double value = (double) microdegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); + } + /// + /// Get RotationalSpeed from MicroradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) + { + double value = (double) microradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); + } + /// + /// Get RotationalSpeed from MillidegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) + { + double value = (double) millidegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); + } + /// + /// Get RotationalSpeed from MilliradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) + { + double value = (double) milliradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); + } + /// + /// Get RotationalSpeed from NanodegreesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) + { + double value = (double) nanodegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); + } + /// + /// Get RotationalSpeed from NanoradiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) + { + double value = (double) nanoradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); + } + /// + /// Get RotationalSpeed from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) + { + double value = (double) radianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); + } + /// + /// Get RotationalSpeed from RevolutionsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) + { + double value = (double) revolutionsperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); + } + /// + /// Get RotationalSpeed from RevolutionsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) + { + double value = (double) revolutionspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +426,363 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] strin /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalSpeed Parse(string str, [CanBeNull] string cultureName) + public static RotationalSpeed Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalSpeedUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromRadiansPerSecond(x.RadiansPerSecond + y.RadiansPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(RotationalSpeed); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static RotationalSpeedUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to 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."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == RotationalSpeedUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RotationalSpeed. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalSpeedUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . + /// + /// A RotationalSpeed with the specified unit. + public RotationalSpeed ToUnit(RotationalSpeedUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new RotationalSpeed(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalSpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(RotationalSpeedUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs index 4bf0f028cc..61fc5c97dd 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalStiffness + public sealed partial class RotationalStiffness : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessUnit? _unit; + + static RotationalStiffness() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadian. /// @@ -75,28 +80,184 @@ public RotationalStiffness() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private RotationalStiffness(double numericValue, RotationalStiffnessUnit unit) + { + if(unit == RotationalStiffnessUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. + /// + public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; + + /// + /// Represents the largest possible value of RotationalStiffness + /// + public static RotationalStiffness MaxValue => new RotationalStiffness(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalStiffness + /// + public static RotationalStiffness MinValue => new RotationalStiffness(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalStiffness; + + /// + /// All units of measurement for the RotationalStiffness quantity. + /// + public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// + public static RotationalStiffness Zero => new RotationalStiffness(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffness.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get RotationalStiffness in KilonewtonMetersPerRadian. + /// + public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); + + /// + /// Get RotationalStiffness in MeganewtonMetersPerRadian. + /// + public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); + + /// + /// Get RotationalStiffness in NewtonMetersPerRadian. + /// + public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get RotationalStiffness from KilonewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromKilonewtonMetersPerRadian(double kilonewtonmetersperradian) + { + double value = (double) kilonewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from MeganewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromMeganewtonMetersPerRadian(double meganewtonmetersperradian) + { + double value = (double) meganewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from NewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffness FromNewtonMetersPerRadian(double newtonmetersperradian) + { + double value = (double) newtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// RotationalStiffness unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) + { + return new RotationalStiffness((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalStiffness Parse(string str, [CanBeNull] string cultureName) + public static RotationalStiffness Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalStiffnessUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMetersPerRadian(x.NewtonMetersPerRadian + y.NewtonMetersPerRadian)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(RotationalStiffness); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static RotationalStiffnessUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static RotationalStiffnessUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == RotationalStiffnessUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . + /// + /// A RotationalStiffness with the specified unit. + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new RotationalStiffness(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; + case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; + case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(RotationalStiffnessUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; + case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; + case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs index 8f07a81fee..2e47b2cfe3 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalStiffnessPerLength + public sealed partial class RotationalStiffnessPerLength : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessPerLengthUnit? _unit; + + static RotationalStiffnessPerLength() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. /// @@ -75,28 +80,184 @@ public RotationalStiffnessPerLength() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private RotationalStiffnessPerLength(double numericValue, RotationalStiffnessPerLengthUnit unit) + { + if(unit == RotationalStiffnessPerLengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. + /// + public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + + /// + /// Represents the largest possible value of RotationalStiffnessPerLength + /// + public static RotationalStiffnessPerLength MaxValue => new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalStiffnessPerLength + /// + public static RotationalStiffnessPerLength MinValue => new RotationalStiffnessPerLength(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; + + /// + /// All units of measurement for the RotationalStiffnessPerLength quantity. + /// + public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// + public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffnessPerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get RotationalStiffnessPerLength in KilonewtonMetersPerRadianPerMeter. + /// + public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + + /// + /// Get RotationalStiffnessPerLength in MeganewtonMetersPerRadianPerMeter. + /// + public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + + /// + /// Get RotationalStiffnessPerLength in NewtonMetersPerRadianPerMeter. + /// + public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double kilonewtonmetersperradianpermeter) + { + double value = (double) kilonewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double meganewtonmetersperradianpermeter) + { + double value = (double) meganewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double newtonmetersperradianpermeter) + { + double value = (double) newtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// RotationalStiffnessPerLength unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) + { + return new RotationalStiffnessPerLength((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +276,343 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [Can /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalStiffnessPerLength Parse(string str, [CanBeNull] string cultureName) + public static RotationalStiffnessPerLength Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalStiffnessPerLengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMetersPerRadianPerMeter(x.NewtonMetersPerRadianPerMeter + y.NewtonMetersPerRadianPerMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(RotationalStiffnessPerLength); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static RotationalStiffnessPerLengthUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == RotationalStiffnessPerLengthUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessPerLengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . + /// + /// A RotationalStiffnessPerLength with the specified unit. + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new RotationalStiffnessPerLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessPerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; + case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; + case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(RotationalStiffnessPerLengthUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; + case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; + case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs index f29c944af5..77bdb7da20 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class SolidAngle : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly SolidAngleUnit? _unit; + + static SolidAngle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit Steradian. /// @@ -75,28 +83,154 @@ public SolidAngle() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private SolidAngle(double numericValue, SolidAngleUnit unit) + { + if(unit == SolidAngleUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. + /// + public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; + + /// + /// Represents the largest possible value of SolidAngle + /// + public static SolidAngle MaxValue => new SolidAngle(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SolidAngle + /// + public static SolidAngle MinValue => new SolidAngle(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SolidAngle; + + /// + /// All units of measurement for the SolidAngle quantity. + /// + public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. + /// + public static SolidAngle Zero => new SolidAngle(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SolidAngle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SolidAngle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SolidAngle in Steradians. + /// + public double Steradians => As(SolidAngleUnit.Steradian); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SolidAngleUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SolidAngle from Steradians. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SolidAngle FromSteradians(double steradians) + { + double value = (double) steradians; + return new SolidAngle(value, SolidAngleUnit.Steradian); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +249,339 @@ public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] string cul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SolidAngle Parse(string str, [CanBeNull] string cultureName) + public static SolidAngle Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SolidAngleUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSteradians(x.Steradians + y.Steradians)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(SolidAngle); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SolidAngleUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SolidAngleUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SolidAngleUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == SolidAngleUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SolidAngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SolidAngleUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs index 1fb196ef50..54b8293db5 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The SpecificEnergy /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class SpecificEnergy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEnergyUnit? _unit; + static SpecificEnergy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerKilogram. /// @@ -75,28 +83,259 @@ public SpecificEnergy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private SpecificEnergy(double numericValue, SpecificEnergyUnit unit) + { + if(unit == SpecificEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. + /// + public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; + + /// + /// Represents the largest possible value of SpecificEnergy + /// + public static SpecificEnergy MaxValue => new SpecificEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificEnergy + /// + public static SpecificEnergy MinValue => new SpecificEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificEnergy; + + /// + /// All units of measurement for the SpecificEnergy quantity. + /// + public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. + /// + public static SpecificEnergy Zero => new SpecificEnergy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificEnergy in CaloriesPerGram. + /// + public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); + + /// + /// Get SpecificEnergy in JoulesPerKilogram. + /// + public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); + + /// + /// Get SpecificEnergy in KilocaloriesPerGram. + /// + public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); + + /// + /// Get SpecificEnergy in KilojoulesPerKilogram. + /// + public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); + + /// + /// Get SpecificEnergy in KilowattHoursPerKilogram. + /// + public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); + + /// + /// Get SpecificEnergy in MegajoulesPerKilogram. + /// + public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); + + /// + /// Get SpecificEnergy in MegawattHoursPerKilogram. + /// + public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); + + /// + /// Get SpecificEnergy in WattHoursPerKilogram. + /// + public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get SpecificEnergy from CaloriesPerGram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) + { + double value = (double) caloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); + } + /// + /// Get SpecificEnergy from JoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) + { + double value = (double) joulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilocaloriesPerGram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) + { + double value = (double) kilocaloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); + } + /// + /// Get SpecificEnergy from KilojoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) + { + double value = (double) kilojoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilowattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) + { + double value = (double) kilowatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); + } + /// + /// Get SpecificEnergy from MegajoulesPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) + { + double value = (double) megajoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); + } + /// + /// Get SpecificEnergy from MegawattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) + { + double value = (double) megawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); + } + /// + /// Get SpecificEnergy from WattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) + { + double value = (double) watthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +354,353 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificEnergy Parse(string str, [CanBeNull] string cultureName) + public static SpecificEnergy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKilogram(x.JoulesPerKilogram + y.JoulesPerKilogram)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(SpecificEnergy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SpecificEnergyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SpecificEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == SpecificEnergyUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return _value; + case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(SpecificEnergyUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; + case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SpecificEnergyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs index 3bb722e5d0..2b5bad71d1 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificEntropy + public sealed partial class SpecificEntropy : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificEntropyUnit? _unit; + static SpecificEntropy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit JoulePerKilogramKelvin. /// @@ -75,28 +80,259 @@ public SpecificEntropy() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private SpecificEntropy(double numericValue, SpecificEntropyUnit unit) + { + if(unit == SpecificEntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. + /// + public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; + + /// + /// Represents the largest possible value of SpecificEntropy + /// + public static SpecificEntropy MaxValue => new SpecificEntropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificEntropy + /// + public static SpecificEntropy MinValue => new SpecificEntropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificEntropy; + + /// + /// All units of measurement for the SpecificEntropy quantity. + /// + public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// + public static SpecificEntropy Zero => new SpecificEntropy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificEntropy in CaloriesPerGramKelvin. + /// + public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); + + /// + /// Get SpecificEntropy in JoulesPerKilogramDegreeCelsius. + /// + public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in JoulesPerKilogramKelvin. + /// + public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); + + /// + /// Get SpecificEntropy in KilocaloriesPerGramKelvin. + /// + public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); + + /// + /// Get SpecificEntropy in KilojoulesPerKilogramDegreeCelsius. + /// + public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in KilojoulesPerKilogramKelvin. + /// + public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); + + /// + /// Get SpecificEntropy in MegajoulesPerKilogramDegreeCelsius. + /// + public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in MegajoulesPerKilogramKelvin. + /// + public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get SpecificEntropy from CaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) + { + double value = (double) caloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) + { + double value = (double) joulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from JoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) + { + double value = (double) joulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from KilocaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) + { + double value = (double) kilocaloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) + { + double value = (double) kilojoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) + { + double value = (double) kilojoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) + { + double value = (double) megajoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) + { + double value = (double) megajoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +351,353 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] strin /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificEntropy Parse(string str, [CanBeNull] string cultureName) + public static SpecificEntropy Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificEntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKilogramKelvin(x.JoulesPerKilogramKelvin + y.JoulesPerKilogramKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(SpecificEntropy); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SpecificEntropyUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SpecificEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == SpecificEntropyUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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(); - return unit; + switch(unit) + { + case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue/4.184e3; + case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; + case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; + case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue/4.184e3) / 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; + case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; + case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SpecificEntropyUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs index 60ed38e097..5ec24394c6 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificVolume + public sealed partial class SpecificVolume : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificVolumeUnit? _unit; + + static SpecificVolume() + { + BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit CubicMeterPerKilogram. /// @@ -75,28 +80,169 @@ public SpecificVolume() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private SpecificVolume(double numericValue, SpecificVolumeUnit unit) + { + if(unit == SpecificVolumeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. + /// + public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; + + /// + /// Represents the largest possible value of SpecificVolume + /// + public static SpecificVolume MaxValue => new SpecificVolume(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificVolume + /// + public static SpecificVolume MinValue => new SpecificVolume(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificVolume; + + /// + /// All units of measurement for the SpecificVolume quantity. + /// + public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// + public static SpecificVolume Zero => new SpecificVolume(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificVolume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificVolume in CubicFeetPerPound. + /// + public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + + /// + /// Get SpecificVolume in CubicMetersPerKilogram. + /// + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificVolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificVolume from CubicFeetPerPound. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificVolume FromCubicFeetPerPound(double cubicfeetperpound) + { + double value = (double) cubicfeetperpound; + return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); + } + /// + /// Get SpecificVolume from CubicMetersPerKilogram. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) + { + double value = (double) cubicmetersperkilogram; + return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +261,341 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificVolume Parse(string str, [CanBeNull] string cultureName) + public static SpecificVolume Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificVolumeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerKilogram(x.CubicMetersPerKilogram + y.CubicMetersPerKilogram)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(SpecificVolume); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SpecificVolumeUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SpecificVolumeUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == SpecificVolumeUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificVolumeUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this SpecificVolume to another SpecificVolume with the unit representation . + /// + /// A SpecificVolume with the specified unit. + public SpecificVolume ToUnit(SpecificVolumeUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new SpecificVolume(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificVolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpecificVolumeUnit.CubicFootPerPound: return _value/16.01846353; + case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(SpecificVolumeUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue*16.01846353; + case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SpecificVolumeUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs index 142cd79d25..6d8f47f547 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class SpecificWeight : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificWeightUnit? _unit; + static SpecificWeight() + { + BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonPerCubicMeter. /// @@ -75,28 +83,394 @@ public SpecificWeight() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private SpecificWeight(double numericValue, SpecificWeightUnit unit) + { + if(unit == SpecificWeightUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. + /// + public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; + + /// + /// Represents the largest possible value of SpecificWeight + /// + public static SpecificWeight MaxValue => new SpecificWeight(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificWeight + /// + public static SpecificWeight MinValue => new SpecificWeight(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificWeight; + + /// + /// All units of measurement for the SpecificWeight quantity. + /// + public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// + public static SpecificWeight Zero => new SpecificWeight(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificWeight.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificWeight in KilogramsForcePerCubicCentimeter. + /// + public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); + + /// + /// Get SpecificWeight in KilogramsForcePerCubicMeter. + /// + public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); + + /// + /// Get SpecificWeight in KilogramsForcePerCubicMillimeter. + /// + public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicCentimeter. + /// + public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicMeter. + /// + public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicMillimeter. + /// + public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); + + /// + /// Get SpecificWeight in KilopoundsForcePerCubicFoot. + /// + public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); + + /// + /// Get SpecificWeight in KilopoundsForcePerCubicInch. + /// + public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); + + /// + /// Get SpecificWeight in MeganewtonsPerCubicMeter. + /// + public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicCentimeter. + /// + public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicMeter. + /// + public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicMillimeter. + /// + public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); + + /// + /// Get SpecificWeight in PoundsForcePerCubicFoot. + /// + public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); + + /// + /// Get SpecificWeight in PoundsForcePerCubicInch. + /// + public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); + + /// + /// Get SpecificWeight in TonnesForcePerCubicCentimeter. + /// + public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); + + /// + /// Get SpecificWeight in TonnesForcePerCubicMeter. + /// + public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); + + /// + /// Get SpecificWeight in TonnesForcePerCubicMillimeter. + /// + public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificWeightUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) + { + double value = (double) kilogramsforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) + { + double value = (double) kilogramsforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); + } + /// + /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) + { + double value = (double) kilogramsforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) + { + double value = (double) kilonewtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) + { + double value = (double) kilonewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) + { + double value = (double) kilonewtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) + { + double value = (double) kilopoundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from KilopoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) + { + double value = (double) kilopoundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from MeganewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromMeganewtonsPerCubicMeter(double meganewtonspercubicmeter) + { + double value = (double) meganewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) + { + double value = (double) newtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) + { + double value = (double) newtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); + } + /// + /// Get SpecificWeight from NewtonsPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) + { + double value = (double) newtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) + { + double value = (double) poundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) + { + double value = (double) poundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicCentimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) + { + double value = (double) tonnesforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) + { + double value = (double) tonnesforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) + { + double value = (double) tonnesforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +489,371 @@ public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] string /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificWeight Parse(string str, [CanBeNull] string cultureName) + public static SpecificWeight Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificWeightUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerCubicMeter(x.NewtonsPerCubicMeter + y.NewtonsPerCubicMeter)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(SpecificWeight); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SpecificWeightUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SpecificWeightUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - if (unit == SpecificWeightUnit.Undefined) + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificWeight. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificWeightUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this SpecificWeight to another SpecificWeight with the unit representation . + /// + /// A SpecificWeight with the specified unit. + public SpecificWeight ToUnit(SpecificWeightUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new SpecificWeight(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificWeightUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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."); } + } - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SpecificWeightUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs index 761ba4fbe3..c7b3ec280e 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Speed + public sealed partial class Speed : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly SpeedUnit? _unit; + + static Speed() + { + BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit MeterPerSecond. /// @@ -75,28 +80,619 @@ public Speed() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Speed(double numericValue, SpeedUnit unit) + { + if(unit == SpeedUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. + /// + public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; + + /// + /// Represents the largest possible value of Speed + /// + public static Speed MaxValue => new Speed(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Speed + /// + public static Speed MinValue => new Speed(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Speed; + + /// + /// All units of measurement for the Speed quantity. + /// + public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. + /// + public static Speed Zero => new Speed(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Speed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Speed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Speed in CentimetersPerHour. + /// + public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); + + /// + /// Get Speed in CentimetersPerMinutes. + /// + public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); + + /// + /// Get Speed in CentimetersPerSecond. + /// + public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); + + /// + /// Get Speed in DecimetersPerMinutes. + /// + public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); + + /// + /// Get Speed in DecimetersPerSecond. + /// + public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); + + /// + /// Get Speed in FeetPerHour. + /// + public double FeetPerHour => As(SpeedUnit.FootPerHour); + + /// + /// Get Speed in FeetPerMinute. + /// + public double FeetPerMinute => As(SpeedUnit.FootPerMinute); + + /// + /// Get Speed in FeetPerSecond. + /// + public double FeetPerSecond => As(SpeedUnit.FootPerSecond); + + /// + /// Get Speed in InchesPerHour. + /// + public double InchesPerHour => As(SpeedUnit.InchPerHour); + + /// + /// Get Speed in InchesPerMinute. + /// + public double InchesPerMinute => As(SpeedUnit.InchPerMinute); + + /// + /// Get Speed in InchesPerSecond. + /// + public double InchesPerSecond => As(SpeedUnit.InchPerSecond); + + /// + /// Get Speed in KilometersPerHour. + /// + public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); + + /// + /// Get Speed in KilometersPerMinutes. + /// + public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); + + /// + /// Get Speed in KilometersPerSecond. + /// + public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); + + /// + /// Get Speed in Knots. + /// + public double Knots => As(SpeedUnit.Knot); + + /// + /// Get Speed in MetersPerHour. + /// + public double MetersPerHour => As(SpeedUnit.MeterPerHour); + + /// + /// Get Speed in MetersPerMinutes. + /// + public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); + + /// + /// Get Speed in MetersPerSecond. + /// + public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); + + /// + /// Get Speed in MicrometersPerMinutes. + /// + public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); + + /// + /// Get Speed in MicrometersPerSecond. + /// + public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); + + /// + /// Get Speed in MilesPerHour. + /// + public double MilesPerHour => As(SpeedUnit.MilePerHour); + + /// + /// Get Speed in MillimetersPerHour. + /// + public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); + + /// + /// Get Speed in MillimetersPerMinutes. + /// + public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); + + /// + /// Get Speed in MillimetersPerSecond. + /// + public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); + + /// + /// Get Speed in NanometersPerMinutes. + /// + public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); + + /// + /// Get Speed in NanometersPerSecond. + /// + public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); + + /// + /// Get Speed in UsSurveyFeetPerHour. + /// + public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); + + /// + /// Get Speed in UsSurveyFeetPerMinute. + /// + public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); + + /// + /// Get Speed in UsSurveyFeetPerSecond. + /// + public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); + + /// + /// Get Speed in YardsPerHour. + /// + public double YardsPerHour => As(SpeedUnit.YardPerHour); + + /// + /// Get Speed in YardsPerMinute. + /// + public double YardsPerMinute => As(SpeedUnit.YardPerMinute); + + /// + /// Get Speed in YardsPerSecond. + /// + public double YardsPerSecond => As(SpeedUnit.YardPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get Speed from CentimetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerHour(double centimetersperhour) + { + double value = (double) centimetersperhour; + return new Speed(value, SpeedUnit.CentimeterPerHour); + } + /// + /// Get Speed from CentimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerMinutes(double centimetersperminutes) + { + double value = (double) centimetersperminutes; + return new Speed(value, SpeedUnit.CentimeterPerMinute); + } + /// + /// Get Speed from CentimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromCentimetersPerSecond(double centimeterspersecond) + { + double value = (double) centimeterspersecond; + return new Speed(value, SpeedUnit.CentimeterPerSecond); + } + /// + /// Get Speed from DecimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromDecimetersPerMinutes(double decimetersperminutes) + { + double value = (double) decimetersperminutes; + return new Speed(value, SpeedUnit.DecimeterPerMinute); + } + /// + /// Get Speed from DecimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromDecimetersPerSecond(double decimeterspersecond) + { + double value = (double) decimeterspersecond; + return new Speed(value, SpeedUnit.DecimeterPerSecond); + } + /// + /// Get Speed from FeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerHour(double feetperhour) + { + double value = (double) feetperhour; + return new Speed(value, SpeedUnit.FootPerHour); + } + /// + /// Get Speed from FeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerMinute(double feetperminute) + { + double value = (double) feetperminute; + return new Speed(value, SpeedUnit.FootPerMinute); + } + /// + /// Get Speed from FeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromFeetPerSecond(double feetpersecond) + { + double value = (double) feetpersecond; + return new Speed(value, SpeedUnit.FootPerSecond); + } + /// + /// Get Speed from InchesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerHour(double inchesperhour) + { + double value = (double) inchesperhour; + return new Speed(value, SpeedUnit.InchPerHour); + } + /// + /// Get Speed from InchesPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerMinute(double inchesperminute) + { + double value = (double) inchesperminute; + return new Speed(value, SpeedUnit.InchPerMinute); + } + /// + /// Get Speed from InchesPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromInchesPerSecond(double inchespersecond) + { + double value = (double) inchespersecond; + return new Speed(value, SpeedUnit.InchPerSecond); } + /// + /// Get Speed from KilometersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerHour(double kilometersperhour) + { + double value = (double) kilometersperhour; + return new Speed(value, SpeedUnit.KilometerPerHour); + } + /// + /// Get Speed from KilometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerMinutes(double kilometersperminutes) + { + double value = (double) kilometersperminutes; + return new Speed(value, SpeedUnit.KilometerPerMinute); + } + /// + /// Get Speed from KilometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKilometersPerSecond(double kilometerspersecond) + { + double value = (double) kilometerspersecond; + return new Speed(value, SpeedUnit.KilometerPerSecond); + } + /// + /// Get Speed from Knots. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromKnots(double knots) + { + double value = (double) knots; + return new Speed(value, SpeedUnit.Knot); + } + /// + /// Get Speed from MetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerHour(double metersperhour) + { + double value = (double) metersperhour; + return new Speed(value, SpeedUnit.MeterPerHour); + } + /// + /// Get Speed from MetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerMinutes(double metersperminutes) + { + double value = (double) metersperminutes; + return new Speed(value, SpeedUnit.MeterPerMinute); + } + /// + /// Get Speed from MetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMetersPerSecond(double meterspersecond) + { + double value = (double) meterspersecond; + return new Speed(value, SpeedUnit.MeterPerSecond); + } + /// + /// Get Speed from MicrometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMicrometersPerMinutes(double micrometersperminutes) + { + double value = (double) micrometersperminutes; + return new Speed(value, SpeedUnit.MicrometerPerMinute); + } + /// + /// Get Speed from MicrometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMicrometersPerSecond(double micrometerspersecond) + { + double value = (double) micrometerspersecond; + return new Speed(value, SpeedUnit.MicrometerPerSecond); + } + /// + /// Get Speed from MilesPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMilesPerHour(double milesperhour) + { + double value = (double) milesperhour; + return new Speed(value, SpeedUnit.MilePerHour); + } + /// + /// Get Speed from MillimetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerHour(double millimetersperhour) + { + double value = (double) millimetersperhour; + return new Speed(value, SpeedUnit.MillimeterPerHour); + } + /// + /// Get Speed from MillimetersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerMinutes(double millimetersperminutes) + { + double value = (double) millimetersperminutes; + return new Speed(value, SpeedUnit.MillimeterPerMinute); + } + /// + /// Get Speed from MillimetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromMillimetersPerSecond(double millimeterspersecond) + { + double value = (double) millimeterspersecond; + return new Speed(value, SpeedUnit.MillimeterPerSecond); + } + /// + /// Get Speed from NanometersPerMinutes. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromNanometersPerMinutes(double nanometersperminutes) + { + double value = (double) nanometersperminutes; + return new Speed(value, SpeedUnit.NanometerPerMinute); + } + /// + /// Get Speed from NanometersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromNanometersPerSecond(double nanometerspersecond) + { + double value = (double) nanometerspersecond; + return new Speed(value, SpeedUnit.NanometerPerSecond); + } + /// + /// Get Speed from UsSurveyFeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) + { + double value = (double) ussurveyfeetperhour; + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); + } + /// + /// Get Speed from UsSurveyFeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) + { + double value = (double) ussurveyfeetperminute; + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); + } + /// + /// Get Speed from UsSurveyFeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) + { + double value = (double) ussurveyfeetpersecond; + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); + } + /// + /// Get Speed from YardsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerHour(double yardsperhour) + { + double value = (double) yardsperhour; + return new Speed(value, SpeedUnit.YardPerHour); + } + /// + /// Get Speed from YardsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerMinute(double yardsperminute) + { + double value = (double) yardsperminute; + return new Speed(value, SpeedUnit.YardPerMinute); + } + /// + /// Get Speed from YardsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Speed FromYardsPerSecond(double yardspersecond) + { + double value = (double) yardspersecond; + return new Speed(value, SpeedUnit.YardPerSecond); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Speed unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static Speed From(double value, SpeedUnit fromUnit) + { + return new Speed((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +711,401 @@ public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] string cultureN /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Speed Parse(string str, [CanBeNull] string cultureName) + public static Speed Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpeedUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersPerSecond(x.MetersPerSecond + y.MetersPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Speed); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static SpeedUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static SpeedUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpeedUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == SpeedUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; + case SpeedUnit.FootPerHour: return _value*0.3048/3600; + case SpeedUnit.FootPerMinute: return _value*0.3048/60; + case SpeedUnit.FootPerSecond: return _value*0.3048; + case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; + case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; + case SpeedUnit.InchPerSecond: return _value*2.54e-2; + case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; + case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; + case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; + case SpeedUnit.Knot: return _value*0.514444; + case SpeedUnit.MeterPerHour: return _value/3600; + case SpeedUnit.MeterPerMinute: return _value/60; + case SpeedUnit.MeterPerSecond: return _value; + case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; + case SpeedUnit.MilePerHour: return _value*0.44704; + case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; + case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; + case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; + case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; + case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; + case SpeedUnit.YardPerHour: return _value*0.9144/3600; + case SpeedUnit.YardPerMinute: return _value*0.9144/60; + case SpeedUnit.YardPerSecond: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(SpeedUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; + case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; + case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; + case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; + case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; + case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; + case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; + case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; + case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; + case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; + case SpeedUnit.Knot: return baseUnitValue/0.514444; + case SpeedUnit.MeterPerHour: return baseUnitValue*3600; + case SpeedUnit.MeterPerMinute: return baseUnitValue*60; + case SpeedUnit.MeterPerSecond: return baseUnitValue; + case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; + case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; + case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; + case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; + case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; + case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; + case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; + case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; + case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; + case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(SpeedUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs index be55387c1f..77796a121f 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Temperature + public sealed partial class Temperature : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureUnit? _unit; + static Temperature() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit Kelvin. /// @@ -75,28 +80,259 @@ public Temperature() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Temperature(double numericValue, TemperatureUnit unit) + { + if(unit == TemperatureUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Temperature, which is Kelvin. All conversions go via this value. + /// + public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; + + /// + /// Represents the largest possible value of Temperature + /// + public static Temperature MaxValue => new Temperature(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Temperature + /// + public static Temperature MinValue => new Temperature(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Temperature; + + /// + /// All units of measurement for the Temperature quantity. + /// + public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static Temperature Zero => new Temperature(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Temperature.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Temperature.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Temperature in DegreesCelsius. + /// + public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); + + /// + /// Get Temperature in DegreesDelisle. + /// + public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); + + /// + /// Get Temperature in DegreesFahrenheit. + /// + public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); + + /// + /// Get Temperature in DegreesNewton. + /// + public double DegreesNewton => As(TemperatureUnit.DegreeNewton); + + /// + /// Get Temperature in DegreesRankine. + /// + public double DegreesRankine => As(TemperatureUnit.DegreeRankine); + + /// + /// Get Temperature in DegreesReaumur. + /// + public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); + + /// + /// Get Temperature in DegreesRoemer. + /// + public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); + + /// + /// Get Temperature in Kelvins. + /// + public double Kelvins => As(TemperatureUnit.Kelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get Temperature from DegreesCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesCelsius(double degreescelsius) + { + double value = (double) degreescelsius; + return new Temperature(value, TemperatureUnit.DegreeCelsius); + } + /// + /// Get Temperature from DegreesDelisle. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesDelisle(double degreesdelisle) + { + double value = (double) degreesdelisle; + return new Temperature(value, TemperatureUnit.DegreeDelisle); + } + /// + /// Get Temperature from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); + } + /// + /// Get Temperature from DegreesNewton. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesNewton(double degreesnewton) + { + double value = (double) degreesnewton; + return new Temperature(value, TemperatureUnit.DegreeNewton); + } + /// + /// Get Temperature from DegreesRankine. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesRankine(double degreesrankine) + { + double value = (double) degreesrankine; + return new Temperature(value, TemperatureUnit.DegreeRankine); + } + /// + /// Get Temperature from DegreesReaumur. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesReaumur(double degreesreaumur) + { + double value = (double) degreesreaumur; + return new Temperature(value, TemperatureUnit.DegreeReaumur); + } + /// + /// Get Temperature from DegreesRoemer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromDegreesRoemer(double degreesroemer) + { + double value = (double) degreesroemer; + return new Temperature(value, TemperatureUnit.DegreeRoemer); + } + /// + /// Get Temperature from Kelvins. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Temperature FromKelvins(double kelvins) + { + double value = (double) kelvins; + return new Temperature(value, TemperatureUnit.Kelvin); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +351,353 @@ public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] string cu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Temperature Parse(string str, [CanBeNull] string cultureName) + public static Temperature Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Temperature); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static TemperatureUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static TemperatureUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == TemperatureUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TemperatureUnit.DegreeCelsius: return _value + 273.15; + case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; + case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; + case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; + case TemperatureUnit.DegreeRankine: return _value*5/9; + case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; + case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; + case TemperatureUnit.Kelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(TemperatureUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; + case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; + case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; + case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; + case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; + case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; + case TemperatureUnit.Kelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(TemperatureUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs index 53014f02b2..0c244aa4d8 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TemperatureChangeRate + public sealed partial class TemperatureChangeRate : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureChangeRateUnit? _unit; + + static TemperatureChangeRate() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. /// @@ -75,28 +80,289 @@ public TemperatureChangeRate() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private TemperatureChangeRate(double numericValue, TemperatureChangeRateUnit unit) + { + if(unit == TemperatureChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. + /// + public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + + /// + /// Represents the largest possible value of TemperatureChangeRate + /// + public static TemperatureChangeRate MaxValue => new TemperatureChangeRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of TemperatureChangeRate + /// + public static TemperatureChangeRate MinValue => new TemperatureChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.TemperatureChangeRate; + + /// + /// All units of measurement for the TemperatureChangeRate quantity. + /// + public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// + public static TemperatureChangeRate Zero => new TemperatureChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get TemperatureChangeRate in CentidegreesCelsiusPerSecond. + /// + public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DecadegreesCelsiusPerSecond. + /// + public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DecidegreesCelsiusPerSecond. + /// + public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DegreesCelsiusPerMinute. + /// + public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + + /// + /// Get TemperatureChangeRate in DegreesCelsiusPerSecond. + /// + public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in HectodegreesCelsiusPerSecond. + /// + public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in KilodegreesCelsiusPerSecond. + /// + public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in MicrodegreesCelsiusPerSecond. + /// + public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in MillidegreesCelsiusPerSecond. + /// + public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in NanodegreesCelsiusPerSecond. + /// + public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) + { + double value = (double) centidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) + { + double value = (double) decadegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) + { + double value = (double) decidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) + { + double value = (double) degreescelsiusperminute; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + } + /// + /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) + { + double value = (double) degreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) + { + double value = (double) hectodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) + { + double value = (double) kilodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) + { + double value = (double) microdegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) + { + double value = (double) millidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) + { + double value = (double) nanodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +381,357 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static TemperatureChangeRate Parse(string str, [CanBeNull] string cultureName) + public static TemperatureChangeRate Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegreesCelsiusPerSecond(x.DegreesCelsiusPerSecond + y.DegreesCelsiusPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(TemperatureChangeRate); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static TemperatureChangeRateUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == TemperatureChangeRateUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . + /// + /// A TemperatureChangeRate with the specified unit. + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new TemperatureChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs index a2ebc7ac84..f5343b234c 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Difference between two temperatures. The conversions are different than for Temperature. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TemperatureDelta + public sealed partial class TemperatureDelta : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureDeltaUnit? _unit; + static TemperatureDelta() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit Kelvin. /// @@ -75,28 +80,259 @@ public TemperatureDelta() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private TemperatureDelta(double numericValue, TemperatureDeltaUnit unit) + { + if(unit == TemperatureDeltaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. + /// + public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; + + /// + /// Represents the largest possible value of TemperatureDelta + /// + public static TemperatureDelta MaxValue => new TemperatureDelta(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of TemperatureDelta + /// + public static TemperatureDelta MinValue => new TemperatureDelta(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.TemperatureDelta; + + /// + /// All units of measurement for the TemperatureDelta quantity. + /// + public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static TemperatureDelta Zero => new TemperatureDelta(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureDelta.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get TemperatureDelta in DegreesCelsius. + /// + public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); + + /// + /// Get TemperatureDelta in DegreesDelisle. + /// + public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); + + /// + /// Get TemperatureDelta in DegreesFahrenheit. + /// + public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); + + /// + /// Get TemperatureDelta in DegreesNewton. + /// + public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); + + /// + /// Get TemperatureDelta in DegreesRankine. + /// + public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); + + /// + /// Get TemperatureDelta in DegreesReaumur. + /// + public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); + + /// + /// Get TemperatureDelta in DegreesRoemer. + /// + public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); + + /// + /// Get TemperatureDelta in Kelvins. + /// + public double Kelvins => As(TemperatureDeltaUnit.Kelvin); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Get TemperatureDelta from DegreesCelsius. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesCelsius(double degreescelsius) + { + double value = (double) degreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); + } + /// + /// Get TemperatureDelta from DegreesDelisle. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) + { + double value = (double) degreesdelisle; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); + } + /// + /// Get TemperatureDelta from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); + } + /// + /// Get TemperatureDelta from DegreesNewton. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesNewton(double degreesnewton) + { + double value = (double) degreesnewton; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); + } + /// + /// Get TemperatureDelta from DegreesRankine. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesRankine(double degreesrankine) + { + double value = (double) degreesrankine; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); + } + /// + /// Get TemperatureDelta from DegreesReaumur. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) + { + double value = (double) degreesreaumur; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); + } + /// + /// Get TemperatureDelta from DegreesRoemer. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromDegreesRoemer(double degreesroemer) + { + double value = (double) degreesroemer; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); + } + /// + /// Get TemperatureDelta from Kelvins. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static TemperatureDelta FromKelvins(double kelvins) + { + double value = (double) kelvins; + return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); } - #region Parsing + /// + /// 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +351,353 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] stri /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static TemperatureDelta Parse(string str, [CanBeNull] string cultureName) + public static TemperatureDelta Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureDeltaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(TemperatureDelta); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static TemperatureDeltaUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 { QuantityType, Value, Unit }.GetHashCode(); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureDeltaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - if (unit == TemperatureDeltaUnit.Undefined) + /// + /// 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) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureDeltaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TemperatureDeltaUnit.DegreeCelsius: return _value; + case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; + case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; + case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; + case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; + case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; + case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; + case TemperatureDeltaUnit.Kelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(TemperatureDeltaUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; + case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; + case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; + case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; + case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; + case TemperatureDeltaUnit.Kelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs index 319d539066..aaa091df43 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,28 @@ namespace UnitsNet /// /// Thermal conductivity is the property of a material to conduct heat. /// - // ReSharper disable once PartialTypeWithSinglePart - + /// + /// 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 + public sealed partial class ThermalConductivity : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalConductivityUnit? _unit; + + static ThermalConductivity() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit WattPerMeterKelvin. /// @@ -75,28 +83,169 @@ public ThermalConductivity() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ThermalConductivity(double numericValue, ThermalConductivityUnit unit) + { + if(unit == ThermalConductivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. + /// + public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; + + /// + /// Represents the largest possible value of ThermalConductivity + /// + public static ThermalConductivity MaxValue => new ThermalConductivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ThermalConductivity + /// + public static ThermalConductivity MinValue => new ThermalConductivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ThermalConductivity; + + /// + /// All units of measurement for the ThermalConductivity quantity. + /// + public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// + public static ThermalConductivity Zero => new ThermalConductivity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ThermalConductivity in BtusPerHourFootFahrenheit. + /// + public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + + /// + /// Get ThermalConductivity in WattsPerMeterKelvin. + /// + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalConductivity from BtusPerHourFootFahrenheit. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalConductivity FromBtusPerHourFootFahrenheit(double btusperhourfootfahrenheit) + { + double value = (double) btusperhourfootfahrenheit; + return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); + } + /// + /// Get ThermalConductivity from WattsPerMeterKelvin. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) + { + double value = (double) wattspermeterkelvin; + return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +264,341 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] s /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ThermalConductivity Parse(string str, [CanBeNull] string cultureName) + public static ThermalConductivity Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ThermalConductivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerMeterKelvin(x.WattsPerMeterKelvin + y.WattsPerMeterKelvin)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ThermalConductivity); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ThermalConductivityUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ThermalConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.TryParse(str, provider, out unit); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + #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)); - if (unit == ThermalConductivityUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalConductivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . + /// + /// A ThermalConductivity with the specified unit. + public ThermalConductivity ToUnit(ThermalConductivityUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ThermalConductivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ThermalConductivityUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs index 4025d018a6..ba41692a9b 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ThermalResistance + public sealed partial class ThermalResistance : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalResistanceUnit? _unit; + static ThermalResistance() + { + BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. /// @@ -75,28 +80,214 @@ public ThermalResistance() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private ThermalResistance(double numericValue, ThermalResistanceUnit unit) + { + if(unit == ThermalResistanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. + /// + public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; + + /// + /// Represents the largest possible value of ThermalResistance + /// + public static ThermalResistance MaxValue => new ThermalResistance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ThermalResistance + /// + public static ThermalResistance MinValue => new ThermalResistance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ThermalResistance; + + /// + /// All units of measurement for the ThermalResistance quantity. + /// + public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// + public static ThermalResistance Zero => new ThermalResistance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ThermalResistance in HourSquareFeetDegreesFahrenheitPerBtu. + /// + public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + + /// + /// Get ThermalResistance in SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + + /// + /// Get ThermalResistance in SquareCentimeterKelvinsPerWatt. + /// + public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + + /// + /// Get ThermalResistance in SquareMeterDegreesCelsiusPerWatt. + /// + public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + + /// + /// Get ThermalResistance in SquareMeterKelvinsPerKilowatt. + /// + public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) + { + double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + } + /// + /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) + { + double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + } + /// + /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) + { + double value = (double) squarecentimeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) + { + double value = (double) squaremeterdegreescelsiusperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); } + /// + /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) + { + double value = (double) squaremeterkelvinsperkilowatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// ThermalResistance unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) + { + return new ThermalResistance((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +306,347 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] str /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ThermalResistance Parse(string str, [CanBeNull] string cultureName) + public static ThermalResistance Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ThermalResistanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMeterKelvinsPerKilowatt(x.SquareMeterKelvinsPerKilowatt + y.SquareMeterKelvinsPerKilowatt)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(ThermalResistance); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static ThermalResistanceUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static ThermalResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + [Windows.Foundation.Metadata.DefaultOverload] + public override bool Equals(object obj) + { + if(obj is null || !(obj is ThermalResistance objThermalResistance)) + return false; - if (unit == ThermalResistanceUnit.Undefined) + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalResistanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this ThermalResistance to another ThermalResistance with the unit representation . + /// + /// A ThermalResistance with the specified unit. + public ThermalResistance ToUnit(ThermalResistanceUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new ThermalResistance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(ThermalResistanceUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(ThermalResistanceUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs index e157f03a47..b94c2afb09 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Torque + public sealed partial class Torque : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly TorqueUnit? _unit; + + static Torque() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit NewtonMeter. /// @@ -75,28 +80,454 @@ public Torque() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Torque(double numericValue, TorqueUnit unit) + { + if(unit == TorqueUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. + /// + public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; + + /// + /// Represents the largest possible value of Torque + /// + public static Torque MaxValue => new Torque(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Torque + /// + public static Torque MinValue => new Torque(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Torque; + + /// + /// All units of measurement for the Torque quantity. + /// + public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. + /// + public static Torque Zero => new Torque(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Torque.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Torque.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Torque in KilogramForceCentimeters. + /// + public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); + + /// + /// Get Torque in KilogramForceMeters. + /// + public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); + + /// + /// Get Torque in KilogramForceMillimeters. + /// + public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); + + /// + /// Get Torque in KilonewtonCentimeters. + /// + public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); + + /// + /// Get Torque in KilonewtonMeters. + /// + public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); + + /// + /// Get Torque in KilonewtonMillimeters. + /// + public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); + + /// + /// Get Torque in KilopoundForceFeet. + /// + public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); + + /// + /// Get Torque in KilopoundForceInches. + /// + public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); + + /// + /// Get Torque in MeganewtonCentimeters. + /// + public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); + + /// + /// Get Torque in MeganewtonMeters. + /// + public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); + + /// + /// Get Torque in MeganewtonMillimeters. + /// + public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); + + /// + /// Get Torque in MegapoundForceFeet. + /// + public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); + + /// + /// Get Torque in MegapoundForceInches. + /// + public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); + + /// + /// Get Torque in NewtonCentimeters. + /// + public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); + + /// + /// Get Torque in NewtonMeters. + /// + public double NewtonMeters => As(TorqueUnit.NewtonMeter); + + /// + /// Get Torque in NewtonMillimeters. + /// + public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); + + /// + /// Get Torque in PoundForceFeet. + /// + public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); + + /// + /// Get Torque in PoundForceInches. + /// + public double PoundForceInches => As(TorqueUnit.PoundForceInch); + + /// + /// Get Torque in TonneForceCentimeters. + /// + public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); + + /// + /// Get Torque in TonneForceMeters. + /// + public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); + + /// + /// Get Torque in TonneForceMillimeters. + /// + public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TorqueUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Torque from KilogramForceCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) + { + double value = (double) kilogramforcecentimeters; + return new Torque(value, TorqueUnit.KilogramForceCentimeter); + } + /// + /// Get Torque from KilogramForceMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceMeters(double kilogramforcemeters) + { + double value = (double) kilogramforcemeters; + return new Torque(value, TorqueUnit.KilogramForceMeter); + } + /// + /// Get Torque from KilogramForceMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) + { + double value = (double) kilogramforcemillimeters; + return new Torque(value, TorqueUnit.KilogramForceMillimeter); + } + /// + /// Get Torque from KilonewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) + { + double value = (double) kilonewtoncentimeters; + return new Torque(value, TorqueUnit.KilonewtonCentimeter); + } + /// + /// Get Torque from KilonewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonMeters(double kilonewtonmeters) + { + double value = (double) kilonewtonmeters; + return new Torque(value, TorqueUnit.KilonewtonMeter); + } + /// + /// Get Torque from KilonewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) + { + double value = (double) kilonewtonmillimeters; + return new Torque(value, TorqueUnit.KilonewtonMillimeter); + } + /// + /// Get Torque from KilopoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) + { + double value = (double) kilopoundforcefeet; + return new Torque(value, TorqueUnit.KilopoundForceFoot); + } + /// + /// Get Torque from KilopoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromKilopoundForceInches(double kilopoundforceinches) + { + double value = (double) kilopoundforceinches; + return new Torque(value, TorqueUnit.KilopoundForceInch); + } + /// + /// Get Torque from MeganewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) + { + double value = (double) meganewtoncentimeters; + return new Torque(value, TorqueUnit.MeganewtonCentimeter); + } + /// + /// Get Torque from MeganewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonMeters(double meganewtonmeters) + { + double value = (double) meganewtonmeters; + return new Torque(value, TorqueUnit.MeganewtonMeter); + } + /// + /// Get Torque from MeganewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) + { + double value = (double) meganewtonmillimeters; + return new Torque(value, TorqueUnit.MeganewtonMillimeter); + } + /// + /// Get Torque from MegapoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMegapoundForceFeet(double megapoundforcefeet) + { + double value = (double) megapoundforcefeet; + return new Torque(value, TorqueUnit.MegapoundForceFoot); + } + /// + /// Get Torque from MegapoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromMegapoundForceInches(double megapoundforceinches) + { + double value = (double) megapoundforceinches; + return new Torque(value, TorqueUnit.MegapoundForceInch); + } + /// + /// Get Torque from NewtonCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonCentimeters(double newtoncentimeters) + { + double value = (double) newtoncentimeters; + return new Torque(value, TorqueUnit.NewtonCentimeter); + } + /// + /// Get Torque from NewtonMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonMeters(double newtonmeters) + { + double value = (double) newtonmeters; + return new Torque(value, TorqueUnit.NewtonMeter); + } + /// + /// Get Torque from NewtonMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromNewtonMillimeters(double newtonmillimeters) + { + double value = (double) newtonmillimeters; + return new Torque(value, TorqueUnit.NewtonMillimeter); + } + /// + /// Get Torque from PoundForceFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromPoundForceFeet(double poundforcefeet) + { + double value = (double) poundforcefeet; + return new Torque(value, TorqueUnit.PoundForceFoot); + } + /// + /// Get Torque from PoundForceInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromPoundForceInches(double poundforceinches) + { + double value = (double) poundforceinches; + return new Torque(value, TorqueUnit.PoundForceInch); + } + /// + /// Get Torque from TonneForceCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) + { + double value = (double) tonneforcecentimeters; + return new Torque(value, TorqueUnit.TonneForceCentimeter); + } + /// + /// Get Torque from TonneForceMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceMeters(double tonneforcemeters) + { + double value = (double) tonneforcemeters; + return new Torque(value, TorqueUnit.TonneForceMeter); + } + /// + /// Get Torque from TonneForceMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) + { + double value = (double) tonneforcemillimeters; + return new Torque(value, TorqueUnit.TonneForceMillimeter); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +546,379 @@ public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] string culture /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Torque Parse(string str, [CanBeNull] string cultureName) + public static Torque Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TorqueUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMeters(x.NewtonMeters + y.NewtonMeters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Torque); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static TorqueUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static TorqueUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out TorqueUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == TorqueUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TorqueUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Torque to another Torque with the unit representation . + /// + /// A Torque with the specified unit. + public Torque ToUnit(TorqueUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Torque(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TorqueUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TorqueUnit.KilogramForceCentimeter: return _value*0.0980665019960652; + case TorqueUnit.KilogramForceMeter: return _value*9.80665019960652; + case TorqueUnit.KilogramForceMillimeter: return _value*0.00980665019960652; + case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; + case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; + case TorqueUnit.KilopoundForceFoot: return (_value*1.3558179483314) * 1e3d; + case TorqueUnit.KilopoundForceInch: return (_value*1.129848290276167e-1) * 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; + case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; + case TorqueUnit.MegapoundForceFoot: return (_value*1.3558179483314) * 1e6d; + case TorqueUnit.MegapoundForceInch: return (_value*1.129848290276167e-1) * 1e6d; + case TorqueUnit.NewtonCentimeter: return _value*0.01; + case TorqueUnit.NewtonMeter: return _value; + case TorqueUnit.NewtonMillimeter: return _value*0.001; + case TorqueUnit.PoundForceFoot: return _value*1.3558179483314; + case TorqueUnit.PoundForceInch: return _value*1.129848290276167e-1; + case TorqueUnit.TonneForceCentimeter: return _value*98.0665019960652; + case TorqueUnit.TonneForceMeter: return _value*9806.65019960653; + case TorqueUnit.TonneForceMillimeter: return _value*9.80665019960652; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(TorqueUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case TorqueUnit.KilogramForceCentimeter: return baseUnitValue*10.1971619222242; + case TorqueUnit.KilogramForceMeter: return baseUnitValue*0.101971619222242; + case TorqueUnit.KilogramForceMillimeter: return baseUnitValue*101.971619222242; + case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; + case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; + case TorqueUnit.KilopoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e3d; + case TorqueUnit.KilopoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; + case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; + case TorqueUnit.MegapoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e6d; + case TorqueUnit.MegapoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e6d; + case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; + case TorqueUnit.NewtonMeter: return baseUnitValue; + case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; + case TorqueUnit.PoundForceFoot: return baseUnitValue/1.3558179483314; + case TorqueUnit.PoundForceInch: return baseUnitValue/1.129848290276167e-1; + case TorqueUnit.TonneForceCentimeter: return baseUnitValue*0.0101971619222242; + case TorqueUnit.TonneForceMeter: return baseUnitValue*0.000101971619222242; + case TorqueUnit.TonneForceMillimeter: return baseUnitValue*0.101971619222242; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(TorqueUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs index 9c5a83161d..ae58a1d057 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VitaminA + public sealed partial class VitaminA : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly VitaminAUnit? _unit; + + static VitaminA() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// /// Creates the quantity with a value of 0 in the base unit InternationalUnit. /// @@ -75,28 +80,154 @@ public VitaminA() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private VitaminA(double numericValue, VitaminAUnit unit) + { + if(unit == VitaminAUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. + /// + public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; + + /// + /// Represents the largest possible value of VitaminA + /// + public static VitaminA MaxValue => new VitaminA(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of VitaminA + /// + public static VitaminA MinValue => new VitaminA(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.VitaminA; + + /// + /// All units of measurement for the VitaminA quantity. + /// + public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. + /// + public static VitaminA Zero => new VitaminA(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VitaminA.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VitaminA.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VitaminA in InternationalUnits. + /// + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VitaminAUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get VitaminA from InternationalUnits. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VitaminA FromInternationalUnits(double internationalunits) + { + double value = (double) internationalunits; + return new VitaminA(value, VitaminAUnit.InternationalUnit); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +246,339 @@ public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] string cultu /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static VitaminA Parse(string str, [CanBeNull] string cultureName) + public static VitaminA Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VitaminAUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromInternationalUnits(x.InternationalUnits + y.InternationalUnits)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(VitaminA); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static VitaminAUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static VitaminAUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VitaminAUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + /// + /// 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); + } - if (unit == VitaminAUnit.Undefined) + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VitaminAUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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; - return unit; + 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. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(VitaminAUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs index 84d4e028ab..c6aa7afafe 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Volume + public sealed partial class Volume : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeUnit? _unit; + static Volume() + { + BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit CubicMeter. /// @@ -75,28 +80,784 @@ public Volume() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private Volume(double numericValue, VolumeUnit unit) + { + if(unit == VolumeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Volume, which is CubicMeter. All conversions go via this value. + /// + public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; + + /// + /// Represents the largest possible value of Volume + /// + public static Volume MaxValue => new Volume(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Volume + /// + public static Volume MinValue => new Volume(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Volume; + + /// + /// All units of measurement for the Volume quantity. + /// + public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. + /// + public static Volume Zero => new Volume(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Volume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Volume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Volume in AuTablespoons. + /// + public double AuTablespoons => As(VolumeUnit.AuTablespoon); + + /// + /// Get Volume in Centiliters. + /// + public double Centiliters => As(VolumeUnit.Centiliter); + + /// + /// Get Volume in CubicCentimeters. + /// + public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); + + /// + /// Get Volume in CubicDecimeters. + /// + public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); + + /// + /// Get Volume in CubicFeet. + /// + public double CubicFeet => As(VolumeUnit.CubicFoot); + + /// + /// Get Volume in CubicInches. + /// + public double CubicInches => As(VolumeUnit.CubicInch); + + /// + /// Get Volume in CubicKilometers. + /// + public double CubicKilometers => As(VolumeUnit.CubicKilometer); + + /// + /// Get Volume in CubicMeters. + /// + public double CubicMeters => As(VolumeUnit.CubicMeter); + + /// + /// Get Volume in CubicMicrometers. + /// + public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); + + /// + /// Get Volume in CubicMiles. + /// + public double CubicMiles => As(VolumeUnit.CubicMile); + + /// + /// Get Volume in CubicMillimeters. + /// + public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); + + /// + /// Get Volume in CubicYards. + /// + public double CubicYards => As(VolumeUnit.CubicYard); + + /// + /// Get Volume in Deciliters. + /// + public double Deciliters => As(VolumeUnit.Deciliter); + + /// + /// Get Volume in HectocubicFeet. + /// + public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); + + /// + /// Get Volume in HectocubicMeters. + /// + public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); + + /// + /// Get Volume in Hectoliters. + /// + public double Hectoliters => As(VolumeUnit.Hectoliter); + + /// + /// Get Volume in ImperialBeerBarrels. + /// + public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); + + /// + /// Get Volume in ImperialGallons. + /// + public double ImperialGallons => As(VolumeUnit.ImperialGallon); + + /// + /// Get Volume in ImperialOunces. + /// + public double ImperialOunces => As(VolumeUnit.ImperialOunce); + + /// + /// Get Volume in KilocubicFeet. + /// + public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); + + /// + /// Get Volume in KilocubicMeters. + /// + public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); + + /// + /// Get Volume in KiloimperialGallons. + /// + public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); + + /// + /// Get Volume in Kiloliters. + /// + public double Kiloliters => As(VolumeUnit.Kiloliter); + + /// + /// Get Volume in KilousGallons. + /// + public double KilousGallons => As(VolumeUnit.KilousGallon); + + /// + /// Get Volume in Liters. + /// + public double Liters => As(VolumeUnit.Liter); + + /// + /// Get Volume in MegacubicFeet. + /// + public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); + + /// + /// Get Volume in MegaimperialGallons. + /// + public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); + + /// + /// Get Volume in MegausGallons. + /// + public double MegausGallons => As(VolumeUnit.MegausGallon); + + /// + /// Get Volume in MetricCups. + /// + public double MetricCups => As(VolumeUnit.MetricCup); + + /// + /// Get Volume in MetricTeaspoons. + /// + public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); + + /// + /// Get Volume in Microliters. + /// + public double Microliters => As(VolumeUnit.Microliter); + + /// + /// Get Volume in Milliliters. + /// + public double Milliliters => As(VolumeUnit.Milliliter); + + /// + /// Get Volume in OilBarrels. + /// + public double OilBarrels => As(VolumeUnit.OilBarrel); + + /// + /// Get Volume in UkTablespoons. + /// + public double UkTablespoons => As(VolumeUnit.UkTablespoon); + + /// + /// Get Volume in UsBeerBarrels. + /// + public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); + + /// + /// Get Volume in UsCustomaryCups. + /// + public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); + + /// + /// Get Volume in UsGallons. + /// + public double UsGallons => As(VolumeUnit.UsGallon); + + /// + /// Get Volume in UsLegalCups. + /// + public double UsLegalCups => As(VolumeUnit.UsLegalCup); + + /// + /// Get Volume in UsOunces. + /// + public double UsOunces => As(VolumeUnit.UsOunce); + + /// + /// Get Volume in UsPints. + /// + public double UsPints => As(VolumeUnit.UsPint); + + /// + /// Get Volume in UsQuarts. + /// + public double UsQuarts => As(VolumeUnit.UsQuart); + + /// + /// Get Volume in UsTablespoons. + /// + public double UsTablespoons => As(VolumeUnit.UsTablespoon); + + /// + /// Get Volume in UsTeaspoons. + /// + public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] string cultureName) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Volume from AuTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromAuTablespoons(double autablespoons) + { + double value = (double) autablespoons; + return new Volume(value, VolumeUnit.AuTablespoon); + } + /// + /// Get Volume from Centiliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCentiliters(double centiliters) + { + double value = (double) centiliters; + return new Volume(value, VolumeUnit.Centiliter); + } + /// + /// Get Volume from CubicCentimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicCentimeters(double cubiccentimeters) + { + double value = (double) cubiccentimeters; + return new Volume(value, VolumeUnit.CubicCentimeter); + } + /// + /// Get Volume from CubicDecimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicDecimeters(double cubicdecimeters) + { + double value = (double) cubicdecimeters; + return new Volume(value, VolumeUnit.CubicDecimeter); + } + /// + /// Get Volume from CubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicFeet(double cubicfeet) + { + double value = (double) cubicfeet; + return new Volume(value, VolumeUnit.CubicFoot); + } + /// + /// Get Volume from CubicInches. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicInches(double cubicinches) + { + double value = (double) cubicinches; + return new Volume(value, VolumeUnit.CubicInch); + } + /// + /// Get Volume from CubicKilometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicKilometers(double cubickilometers) + { + double value = (double) cubickilometers; + return new Volume(value, VolumeUnit.CubicKilometer); + } + /// + /// Get Volume from CubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMeters(double cubicmeters) + { + double value = (double) cubicmeters; + return new Volume(value, VolumeUnit.CubicMeter); + } + /// + /// Get Volume from CubicMicrometers. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMicrometers(double cubicmicrometers) + { + double value = (double) cubicmicrometers; + return new Volume(value, VolumeUnit.CubicMicrometer); + } + /// + /// Get Volume from CubicMiles. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMiles(double cubicmiles) + { + double value = (double) cubicmiles; + return new Volume(value, VolumeUnit.CubicMile); + } + /// + /// Get Volume from CubicMillimeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicMillimeters(double cubicmillimeters) + { + double value = (double) cubicmillimeters; + return new Volume(value, VolumeUnit.CubicMillimeter); + } + /// + /// Get Volume from CubicYards. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromCubicYards(double cubicyards) + { + double value = (double) cubicyards; + return new Volume(value, VolumeUnit.CubicYard); + } + /// + /// Get Volume from Deciliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromDeciliters(double deciliters) + { + double value = (double) deciliters; + return new Volume(value, VolumeUnit.Deciliter); + } + /// + /// Get Volume from HectocubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectocubicFeet(double hectocubicfeet) + { + double value = (double) hectocubicfeet; + return new Volume(value, VolumeUnit.HectocubicFoot); + } + /// + /// Get Volume from HectocubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectocubicMeters(double hectocubicmeters) + { + double value = (double) hectocubicmeters; + return new Volume(value, VolumeUnit.HectocubicMeter); + } + /// + /// Get Volume from Hectoliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromHectoliters(double hectoliters) + { + double value = (double) hectoliters; + return new Volume(value, VolumeUnit.Hectoliter); + } + /// + /// Get Volume from ImperialBeerBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) + { + double value = (double) imperialbeerbarrels; + return new Volume(value, VolumeUnit.ImperialBeerBarrel); + } + /// + /// Get Volume from ImperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialGallons(double imperialgallons) + { + double value = (double) imperialgallons; + return new Volume(value, VolumeUnit.ImperialGallon); + } + /// + /// Get Volume from ImperialOunces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromImperialOunces(double imperialounces) + { + double value = (double) imperialounces; + return new Volume(value, VolumeUnit.ImperialOunce); + } + /// + /// Get Volume from KilocubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilocubicFeet(double kilocubicfeet) + { + double value = (double) kilocubicfeet; + return new Volume(value, VolumeUnit.KilocubicFoot); + } + /// + /// Get Volume from KilocubicMeters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilocubicMeters(double kilocubicmeters) + { + double value = (double) kilocubicmeters; + return new Volume(value, VolumeUnit.KilocubicMeter); + } + /// + /// Get Volume from KiloimperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKiloimperialGallons(double kiloimperialgallons) + { + double value = (double) kiloimperialgallons; + return new Volume(value, VolumeUnit.KiloimperialGallon); + } + /// + /// Get Volume from Kiloliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKiloliters(double kiloliters) + { + double value = (double) kiloliters; + return new Volume(value, VolumeUnit.Kiloliter); + } + /// + /// Get Volume from KilousGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromKilousGallons(double kilousgallons) + { + double value = (double) kilousgallons; + return new Volume(value, VolumeUnit.KilousGallon); + } + /// + /// Get Volume from Liters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromLiters(double liters) + { + double value = (double) liters; + return new Volume(value, VolumeUnit.Liter); + } + /// + /// Get Volume from MegacubicFeet. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegacubicFeet(double megacubicfeet) + { + double value = (double) megacubicfeet; + return new Volume(value, VolumeUnit.MegacubicFoot); + } + /// + /// Get Volume from MegaimperialGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegaimperialGallons(double megaimperialgallons) + { + double value = (double) megaimperialgallons; + return new Volume(value, VolumeUnit.MegaimperialGallon); + } + /// + /// Get Volume from MegausGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMegausGallons(double megausgallons) + { + double value = (double) megausgallons; + return new Volume(value, VolumeUnit.MegausGallon); + } + /// + /// Get Volume from MetricCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMetricCups(double metriccups) + { + double value = (double) metriccups; + return new Volume(value, VolumeUnit.MetricCup); + } + /// + /// Get Volume from MetricTeaspoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMetricTeaspoons(double metricteaspoons) + { + double value = (double) metricteaspoons; + return new Volume(value, VolumeUnit.MetricTeaspoon); + } + /// + /// Get Volume from Microliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMicroliters(double microliters) + { + double value = (double) microliters; + return new Volume(value, VolumeUnit.Microliter); + } + /// + /// Get Volume from Milliliters. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromMilliliters(double milliliters) + { + double value = (double) milliliters; + return new Volume(value, VolumeUnit.Milliliter); + } + /// + /// Get Volume from OilBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromOilBarrels(double oilbarrels) + { + double value = (double) oilbarrels; + return new Volume(value, VolumeUnit.OilBarrel); + } + /// + /// Get Volume from UkTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUkTablespoons(double uktablespoons) + { + double value = (double) uktablespoons; + return new Volume(value, VolumeUnit.UkTablespoon); + } + /// + /// Get Volume from UsBeerBarrels. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsBeerBarrels(double usbeerbarrels) + { + double value = (double) usbeerbarrels; + return new Volume(value, VolumeUnit.UsBeerBarrel); + } + /// + /// Get Volume from UsCustomaryCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsCustomaryCups(double uscustomarycups) + { + double value = (double) uscustomarycups; + return new Volume(value, VolumeUnit.UsCustomaryCup); + } + /// + /// Get Volume from UsGallons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsGallons(double usgallons) + { + double value = (double) usgallons; + return new Volume(value, VolumeUnit.UsGallon); + } + /// + /// Get Volume from UsLegalCups. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsLegalCups(double uslegalcups) + { + double value = (double) uslegalcups; + return new Volume(value, VolumeUnit.UsLegalCup); + } + /// + /// Get Volume from UsOunces. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsOunces(double usounces) + { + double value = (double) usounces; + return new Volume(value, VolumeUnit.UsOunce); + } + /// + /// Get Volume from UsPints. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsPints(double uspints) + { + double value = (double) uspints; + return new Volume(value, VolumeUnit.UsPint); + } + /// + /// Get Volume from UsQuarts. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsQuarts(double usquarts) + { + double value = (double) usquarts; + return new Volume(value, VolumeUnit.UsQuart); + } + /// + /// Get Volume from UsTablespoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsTablespoons(double ustablespoons) + { + double value = (double) ustablespoons; + return new Volume(value, VolumeUnit.UsTablespoon); + } + /// + /// Get Volume from UsTeaspoons. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static Volume FromUsTeaspoons(double usteaspoons) + { + double value = (double) usteaspoons; + return new Volume(value, VolumeUnit.UsTeaspoon); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// 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); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +876,423 @@ public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] string culture /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Volume Parse(string str, [CanBeNull] string cultureName) + public static Volume Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VolumeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMeters(x.CubicMeters + y.CubicMeters)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(Volume); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static VolumeUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static VolumeUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out VolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == VolumeUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Volume to another Volume with the unit representation . + /// + /// A Volume with the specified unit. + public Volume ToUnit(VolumeUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Volume(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case VolumeUnit.AuTablespoon: return _value*2e-5; + case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; + case VolumeUnit.CubicCentimeter: return _value/1e6; + case VolumeUnit.CubicDecimeter: return _value/1e3; + case VolumeUnit.CubicFoot: return _value*0.0283168; + case VolumeUnit.CubicInch: return _value*1.6387*1e-5; + case VolumeUnit.CubicKilometer: return _value*1e9; + case VolumeUnit.CubicMeter: return _value; + case VolumeUnit.CubicMicrometer: return _value/1e18; + case VolumeUnit.CubicMile: return _value*4.16818182544058e9; + case VolumeUnit.CubicMillimeter: return _value/1e9; + case VolumeUnit.CubicYard: return _value*0.764554858; + case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; + case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; + case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; + case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; + case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; + case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; + case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; + case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; + case VolumeUnit.Kiloliter: return (_value/1e3) * 1e3d; + case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; + case VolumeUnit.Liter: return _value/1e3; + case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; + case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; + case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; + case VolumeUnit.MetricCup: return _value*0.00025; + case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; + case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; + case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; + case VolumeUnit.OilBarrel: return _value*0.158987294928; + case VolumeUnit.UkTablespoon: return _value*1.5e-5; + case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; + case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; + case VolumeUnit.UsGallon: return _value*0.00378541; + case VolumeUnit.UsLegalCup: return _value*0.00024; + case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; + case VolumeUnit.UsPint: return _value*4.73176473e-4; + case VolumeUnit.UsQuart: return _value*9.46352946e-4; + case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(VolumeUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - return unit; + switch(unit) + { + case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; + case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; + case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; + case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; + case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; + case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); + case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; + case VolumeUnit.CubicMeter: return baseUnitValue; + case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; + case VolumeUnit.CubicMile: return baseUnitValue/4.16818182544058e9; + case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; + case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; + case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; + case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; + case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; + case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; + case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; + case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; + case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; + case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; + case VolumeUnit.Kiloliter: return (baseUnitValue*1e3) / 1e3d; + case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; + case VolumeUnit.Liter: return baseUnitValue*1e3; + case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; + case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; + case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; + case VolumeUnit.MetricCup: return baseUnitValue/0.00025; + case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; + case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; + case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; + case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; + case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; + case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; + case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; + case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; + case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; + case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; + case VolumeUnit.UsPint: return baseUnitValue/4.73176473e-4; + case VolumeUnit.UsQuart: return baseUnitValue/9.46352946e-4; + case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(VolumeUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs index 52ec8f1b72..107930d6ef 100644 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs +++ b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.WindowsRuntimeComponent.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,18 +49,25 @@ namespace UnitsNet /// /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. /// - // ReSharper disable once PartialTypeWithSinglePart - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumeFlow + public sealed partial class VolumeFlow : IQuantity { /// /// The numeric value this quantity was constructed with. /// - public double Value => Convert.ToDouble(_value); + private readonly double _value; + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeFlowUnit? _unit; + + static VolumeFlow() + { + BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); + } /// /// Creates the quantity with a value of 0 in the base unit CubicMeterPerSecond. /// @@ -75,28 +80,559 @@ public VolumeFlow() _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + private VolumeFlow(double numericValue, VolumeFlowUnit unit) + { + if(unit == VolumeFlowUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. + /// + public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; + + /// + /// Represents the largest possible value of VolumeFlow + /// + public static VolumeFlow MaxValue => new VolumeFlow(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of VolumeFlow + /// + public static VolumeFlow MinValue => new VolumeFlow(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.VolumeFlow; + + /// + /// All units of measurement for the VolumeFlow quantity. + /// + public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// + public static VolumeFlow Zero => new VolumeFlow(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => Convert.ToDouble(_value); + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VolumeFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VolumeFlow in CentilitersPerMinute. + /// + public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); + + /// + /// Get VolumeFlow in CubicDecimetersPerMinute. + /// + public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); + + /// + /// Get VolumeFlow in CubicFeetPerHour. + /// + public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); + + /// + /// Get VolumeFlow in CubicFeetPerMinute. + /// + public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); + + /// + /// Get VolumeFlow in CubicFeetPerSecond. + /// + public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); + + /// + /// Get VolumeFlow in CubicMetersPerHour. + /// + public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); + + /// + /// Get VolumeFlow in CubicMetersPerMinute. + /// + public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); + + /// + /// Get VolumeFlow in CubicMetersPerSecond. + /// + public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); + + /// + /// Get VolumeFlow in CubicMillimetersPerSecond. + /// + public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); + + /// + /// Get VolumeFlow in CubicYardsPerHour. + /// + public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); + + /// + /// Get VolumeFlow in CubicYardsPerMinute. + /// + public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); + + /// + /// Get VolumeFlow in CubicYardsPerSecond. + /// + public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); + + /// + /// Get VolumeFlow in DecilitersPerMinute. + /// + public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); + + /// + /// Get VolumeFlow in KilolitersPerMinute. + /// + public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); + + /// + /// Get VolumeFlow in KilousGallonsPerMinute. + /// + public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonsPerMinute); + + /// + /// Get VolumeFlow in LitersPerHour. + /// + public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); + + /// + /// Get VolumeFlow in LitersPerMinute. + /// + public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); + + /// + /// Get VolumeFlow in LitersPerSecond. + /// + public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); + + /// + /// Get VolumeFlow in MicrolitersPerMinute. + /// + public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); + + /// + /// Get VolumeFlow in MillilitersPerMinute. + /// + public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); + + /// + /// Get VolumeFlow in MillionUsGallonsPerDay. + /// + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); + + /// + /// Get VolumeFlow in NanolitersPerMinute. + /// + public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); + + /// + /// Get VolumeFlow in OilBarrelsPerDay. + /// + public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); + + /// + /// Get VolumeFlow in OilBarrelsPerHour. + /// + public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); + + /// + /// Get VolumeFlow in OilBarrelsPerMinute. + /// + public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); + + /// + /// Get VolumeFlow in UsGallonsPerHour. + /// + public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); + + /// + /// Get VolumeFlow in UsGallonsPerMinute. + /// + public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); + + /// + /// Get VolumeFlow in UsGallonsPerSecond. + /// + public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); + + #endregion + + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. /// Unit abbreviation string. - [UsedImplicitly] + 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) { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + #region Static Factory Methods + + /// + /// Get VolumeFlow from CentilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) + { + double value = (double) centilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); + } + /// + /// Get VolumeFlow from CubicDecimetersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) + { + double value = (double) cubicdecimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) + { + double value = (double) cubicfeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); + } + /// + /// Get VolumeFlow from CubicFeetPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) + { + double value = (double) cubicfeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); + } + /// + /// Get VolumeFlow from CubicFeetPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) + { + double value = (double) cubicfeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); + } + /// + /// Get VolumeFlow from CubicMetersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) + { + double value = (double) cubicmetersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); + } + /// + /// Get VolumeFlow from CubicMetersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) + { + double value = (double) cubicmetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); + } + /// + /// Get VolumeFlow from CubicMetersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) + { + double value = (double) cubicmeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); + } + /// + /// Get VolumeFlow from CubicMillimetersPerSecond. + /// + /// 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); } + /// + /// Get VolumeFlow from CubicYardsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) + { + double value = (double) cubicyardsperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); + } + /// + /// Get VolumeFlow from CubicYardsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) + { + double value = (double) cubicyardsperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); + } + /// + /// Get VolumeFlow from CubicYardsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) + { + double value = (double) cubicyardspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); + } + /// + /// Get VolumeFlow from DecilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) + { + double value = (double) decilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); + } + /// + /// Get VolumeFlow from KilolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) + { + double value = (double) kilolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); + } + /// + /// Get VolumeFlow from KilousGallonsPerMinute. + /// + /// 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.KilousGallonsPerMinute); + } + /// + /// Get VolumeFlow from LitersPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerHour(double litersperhour) + { + double value = (double) litersperhour; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); + } + /// + /// Get VolumeFlow from LitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerMinute(double litersperminute) + { + double value = (double) litersperminute; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); + } + /// + /// Get VolumeFlow from LitersPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromLitersPerSecond(double literspersecond) + { + double value = (double) literspersecond; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); + } + /// + /// Get VolumeFlow from MicrolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) + { + double value = (double) microlitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); + } + /// + /// Get VolumeFlow from MillilitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) + { + double value = (double) millilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); + } + /// + /// Get VolumeFlow from MillionUsGallonsPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) + { + double value = (double) millionusgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); + } + /// + /// Get VolumeFlow from NanolitersPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) + { + double value = (double) nanolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); + } + /// + /// Get VolumeFlow from OilBarrelsPerDay. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) + { + double value = (double) oilbarrelsperday; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); + } + /// + /// Get VolumeFlow from OilBarrelsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerHour(double oilbarrelsperhour) + { + double value = (double) oilbarrelsperhour; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); + } + /// + /// Get VolumeFlow from OilBarrelsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromOilBarrelsPerMinute(double oilbarrelsperminute) + { + double value = (double) oilbarrelsperminute; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerHour. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) + { + double value = (double) usgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); + } + /// + /// Get VolumeFlow from UsGallonsPerMinute. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) + { + double value = (double) usgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerSecond. + /// + /// If value is NaN or Infinity. + [Windows.Foundation.Metadata.DefaultOverload] + public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) + { + double value = (double) usgallonspersecond; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// VolumeFlow unit value. + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) + { + return new VolumeFlow((double)value, fromUnit); + } + + #endregion - #region Parsing + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -115,140 +651,393 @@ public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] string cul /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static VolumeFlow Parse(string str, [CanBeNull] string cultureName) + public static VolumeFlow Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes 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); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VolumeFlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerSecond(x.CubicMetersPerSecond + y.CubicMetersPerSecond)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// 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) { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default(VolumeFlow); - return false; - } + 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} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static VolumeFlowUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - internal static VolumeFlowUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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) { - if (str == null) throw new ArgumentNullException(nameof(str)); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + 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 - if (unit == VolumeFlowUnit.Undefined) + #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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeFlowUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this VolumeFlow to another VolumeFlow with the unit representation . + /// + /// A VolumeFlow with the specified unit. + public VolumeFlow ToUnit(VolumeFlowUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new VolumeFlow(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case VolumeFlowUnit.CentiliterPerMinute: return (_value/60000.00000) * 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; + case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; + case VolumeFlowUnit.CubicMeterPerSecond: return _value; + case VolumeFlowUnit.CubicMillimeterPerSecond: return _value*1e-9; + case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; + case VolumeFlowUnit.DeciliterPerMinute: return (_value/60000.00000) * 1e-1d; + case VolumeFlowUnit.KiloliterPerMinute: return (_value/60000.00000) * 1e3d; + case VolumeFlowUnit.KilousGallonsPerMinute: return _value/15.850323141489; + case VolumeFlowUnit.LiterPerHour: return _value/3600000.000; + case VolumeFlowUnit.LiterPerMinute: return _value/60000.00000; + case VolumeFlowUnit.LiterPerSecond: return _value/1000; + case VolumeFlowUnit.MicroliterPerMinute: return (_value/60000.00000) * 1e-6d; + case VolumeFlowUnit.MilliliterPerMinute: return (_value/60000.00000) * 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; + case VolumeFlowUnit.NanoliterPerMinute: return (_value/60000.00000) * 1e-9d; + case VolumeFlowUnit.OilBarrelPerDay: return _value*1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.OilBarrelPerHour: return _value*4.41631375e-5; + case VolumeFlowUnit.OilBarrelPerMinute: return _value*2.64978825e-3; + case VolumeFlowUnit.UsGallonPerHour: return _value/951019.38848933424; + case VolumeFlowUnit.UsGallonPerMinute: return _value/15850.323141489; + case VolumeFlowUnit.UsGallonPerSecond: return _value/264.1720523581484; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } + + private double AsBaseNumericType(VolumeFlowUnit unit) + { + if(Unit == unit) + return _value; - return unit; + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case VolumeFlowUnit.CentiliterPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; + case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; + case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; + case VolumeFlowUnit.CubicMillimeterPerSecond: return baseUnitValue/1e-9; + case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; + case VolumeFlowUnit.DeciliterPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; + case VolumeFlowUnit.KiloliterPerMinute: return (baseUnitValue*60000.00000) / 1e3d; + case VolumeFlowUnit.KilousGallonsPerMinute: return baseUnitValue*15.850323141489; + case VolumeFlowUnit.LiterPerHour: return baseUnitValue*3600000.000; + case VolumeFlowUnit.LiterPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.LiterPerSecond: return baseUnitValue*1000; + case VolumeFlowUnit.MicroliterPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; + case VolumeFlowUnit.MilliliterPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; + case VolumeFlowUnit.NanoliterPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; + case VolumeFlowUnit.OilBarrelPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.OilBarrelPerHour: return baseUnitValue/4.41631375e-5; + case VolumeFlowUnit.OilBarrelPerMinute: return baseUnitValue/2.64978825e-3; + case VolumeFlowUnit.UsGallonPerHour: return baseUnitValue*951019.38848933424; + case VolumeFlowUnit.UsGallonPerMinute: return baseUnitValue*15850.323141489; + case VolumeFlowUnit.UsGallonPerSecond: return baseUnitValue*264.1720523581484; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// String representation. - public string ToString(VolumeFlowUnit unit, [CanBeNull] string cultureName) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return ToString(unit, cultureName, 2); + var provider = cultureName; + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); + 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. /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) + /// 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)); - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) + { + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; + } } } diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj index 645817f4cf..e34d1d23a3 100644 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj +++ b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj @@ -19,7 +19,14 @@ false ..\Artifacts\UnitsNet.WindowsRuntimeComponent CS1701;CS1702;CS1705;CS0618;CS0809;CS1591 + 7.3 + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + AnyCPU true @@ -97,7 +104,7 @@ PackageReference - + @@ -121,6 +128,10 @@ 11.1.0 + + + 4.5.0 + diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec index 4af0c2328d..d39cbb50b2 100644 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec +++ b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec @@ -2,7 +2,7 @@ UnitsNet.WindowsRuntimeComponent - 3.111.0 + 4.0.0-beta2 Units.NET - Windows Runtime Component Andreas Gullberg Larsen Andreas Gullberg Larsen diff --git a/UnitsNet.sln b/UnitsNet.sln index b4fa90e778..f827f95b70 100644 --- a/UnitsNet.sln +++ b/UnitsNet.sln @@ -7,10 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet", "UnitsNet\UnitsN EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet", "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj", "{FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.Signed", "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.Signed.csproj", "{7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Signed", "UnitsNet\UnitsNet.Signed.csproj", "{21C1AFDC-354E-4D97-947B-2DB63C529E6E}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.Tests", "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj", "{FFEEDF44-F32D-4D92-A75E-487CB0582EB1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Tests", "UnitsNet.Tests\UnitsNet.Tests.csproj", "{0E3B7567-5DF2-44BD-88DB-CCF050D3F943}" @@ -31,14 +27,6 @@ Global {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Debug|Any CPU.Build.0 = Debug|Any CPU {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|Any CPU.ActiveCfg = Release|Any CPU {FB696BFE-B303-4EBD-A0E6-4A7B19DE429B}.Release|Any CPU.Build.0 = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7798DBCF-DD59-4CAD-A754-FB7DCC6BD312}.Release|Any CPU.Build.0 = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21C1AFDC-354E-4D97-947B-2DB63C529E6E}.Release|Any CPU.Build.0 = Release|Any CPU {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Debug|Any CPU.Build.0 = Debug|Any CPU {FFEEDF44-F32D-4D92-A75E-487CB0582EB1}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/UnitsNet/AmbiguousUnitParseException.cs b/UnitsNet/AmbiguousUnitParseException.cs index 22e6b00489..c59a5a5e12 100644 --- a/UnitsNet/AmbiguousUnitParseException.cs +++ b/UnitsNet/AmbiguousUnitParseException.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,9 +20,16 @@ // THE SOFTWARE. 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. + /// #if WINDOWS_UWP internal #else @@ -30,14 +37,16 @@ namespace UnitsNet #endif class AmbiguousUnitParseException : UnitsNetException { + /// public AmbiguousUnitParseException(string message) : base(message) { HResult = 2; } + /// public AmbiguousUnitParseException(string message, Exception innerException) : base(message, innerException) { HResult = 2; } } -} \ No newline at end of file +} diff --git a/UnitsNet/BaseDimensions.cs b/UnitsNet/BaseDimensions.cs index 8fd78eb208..6ce00d968b 100644 --- a/UnitsNet/BaseDimensions.cs +++ b/UnitsNet/BaseDimensions.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ using System; using System.Text; +using System.Linq; namespace UnitsNet { @@ -29,6 +30,7 @@ namespace UnitsNet /// public sealed class BaseDimensions { + /// public BaseDimensions(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity) { Length = length; @@ -40,37 +42,68 @@ public BaseDimensions(int length, int mass, int time, int current, int temperatu 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 int[]{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 this == Dimensionless; + } + + /// public override bool Equals(object obj) { if(obj is null || !(obj is BaseDimensions)) return false; - var baseDimensionsObj = (BaseDimensions)obj; + var other = (BaseDimensions)obj; - return Length == baseDimensionsObj.Length && - Mass == baseDimensionsObj.Mass && - Time == baseDimensionsObj.Time && - Current == baseDimensionsObj.Current && - Temperature == baseDimensionsObj.Temperature && - Amount == baseDimensionsObj.Amount && - LuminousIntensity == baseDimensionsObj.LuminousIntensity; + 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() { - int hash = 17; - hash = hash * 23 + Length; - hash = hash * 23 + Mass; - hash = hash * 23 + Time; - hash = hash * 23 + Current; - hash = hash * 23 + Temperature; - hash = hash * 23 + Amount; - hash = hash * 23 + LuminousIntensity; - return hash; + 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, @@ -81,8 +114,16 @@ public BaseDimensions Multiply(BaseDimensions right) 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, @@ -94,27 +135,64 @@ public BaseDimensions Divide(BaseDimensions right) } #if !WINDOWS_UWP + + /// + /// Check if two dimensions are equal. + /// + /// Left. + /// Right. + /// True if equal. public static bool operator ==(BaseDimensions left, BaseDimensions right) { - return left.Equals(right); + return left is null ? right is null : left.Equals(right); } - + + /// + /// Check if two dimensions are unequal. + /// + /// Left. + /// Right. + /// True if not equal. public static bool operator !=(BaseDimensions left, BaseDimensions right) { - return !( left == right ); + return !(left == right); } + /// + /// Multiply two dimensions. + /// + /// Left. + /// 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)); + return left.Multiply(right); } + /// + /// Divide two dimensions. + /// + /// Left. + /// 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)); + return left.Divide(right); } + #endif + /// public override string ToString() { var sb = new StringBuilder(); @@ -130,16 +208,16 @@ public override string ToString() return sb.ToString(); } - private static void AppendDimensionString( StringBuilder sb, string name, int value ) + private static void AppendDimensionString(StringBuilder sb, string name, int value) { - var absoluteValue = Math.Abs( value ); + var absoluteValue = Math.Abs(value); - if( absoluteValue > 0 ) + if(absoluteValue > 0) { - sb.AppendFormat( "[{0}]", name ); + sb.AppendFormat("[{0}]", name); - if( absoluteValue > 1 ) - sb.AppendFormat( "^{0}", value ); + if(absoluteValue > 1) + sb.AppendFormat("^{0}", value); } } @@ -177,5 +255,10 @@ private static void AppendDimensionString( StringBuilder sb, string name, int va /// 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/BaseUnits.cs b/UnitsNet/BaseUnits.cs new file mode 100644 index 0000000000..16949c0ff6 --- /dev/null +++ b/UnitsNet/BaseUnits.cs @@ -0,0 +1,177 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Text; +using UnitsNet.Units; + +namespace UnitsNet +{ +#if !WINDOWS_UWP + public sealed partial class BaseUnits : IEquatable { } +#endif + + /// + /// 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 partial 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. +#if WINDOWS_UWP + [Windows.Foundation.Metadata.DefaultOverload] +#endif + 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(); + } + +#if !WINDOWS_UWP + + /// + /// Checks if this instance is equal to another. + /// + /// The left instance. + /// The right instance. + /// True if equal, otherwise false. + /// + public static bool operator ==(BaseUnits left, BaseUnits right) + { + return left is null ? right is null : left.Equals(right); + } + + /// + /// Checks if this instance is not equal to another. + /// + /// The left instance. + /// The right instance. + /// True if not equal, otherwise false. + /// + public static bool operator !=(BaseUnits left, BaseUnits right) + { + return !(left == right); + } + +#endif + + /// + 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/Comparison.cs b/UnitsNet/Comparison.cs index ad3b781afb..acf4add944 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,45 +23,56 @@ 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. + /// 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. - /// + /// 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 - /// + /// 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 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) + if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); - switch(comparisonType) + switch (comparisonType) { case ComparisonType.Relative: return EqualsRelative(referenceValue, otherValue, tolerance); @@ -75,15 +86,18 @@ public static bool Equals(double referenceValue, double otherValue, double toler /// /// 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. - /// + /// 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. @@ -92,24 +106,26 @@ public static bool Equals(double referenceValue, double otherValue, double toler /// 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) + if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); - double maxVariation = Math.Abs(referenceValue * tolerance); + 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 - /// + /// 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. @@ -118,7 +134,7 @@ public static bool EqualsRelative(double referenceValue, double otherValue, doub /// 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) + 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/ComparisonType.cs b/UnitsNet/ComparisonType.cs index 5d9a35ec1e..978de56398 100644 --- a/UnitsNet/ComparisonType.cs +++ b/UnitsNet/ComparisonType.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,7 +26,14 @@ namespace UnitsNet /// public enum ComparisonType { + /// + /// Error margin in relative size to a reference value. + /// Relative, + + /// + /// Error margin as absolute size. + /// Absolute } } diff --git a/UnitsNet/CustomCode/Extensions/AmplitudeRatioExtensions.cs b/UnitsNet/CustomCode/Extensions/AmplitudeRatioExtensions.cs deleted file mode 100644 index 6dfc38e269..0000000000 --- a/UnitsNet/CustomCode/Extensions/AmplitudeRatioExtensions.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace UnitsNet.CustomCode.Extensions -{ - /// - /// Extension methods for . - /// - public static class AmplitudeRatioExtensions - { - /// - /// Gets an from . - /// - /// The amplitude ratio to convert. - /// - /// Provides a nicer syntax for converting an amplitude ratio back to a voltage. - /// - /// var voltage = voltageRatio.ToElectricPotential(); - /// - /// - public static ElectricPotential ToElectricPotential(this AmplitudeRatio amplitudeRatio) - { - return AmplitudeRatio.ToElectricPotential(amplitudeRatio); - } - - /// - /// Converts a to a . - /// - /// The amplitude ratio to convert. - /// 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 static PowerRatio ToPowerRatio(this AmplitudeRatio amplitudeRatio, ElectricResistance impedance) - { - return AmplitudeRatio.ToPowerRatio(amplitudeRatio, impedance); - } - } -} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Extensions/MolarityExtensions.cs b/UnitsNet/CustomCode/Extensions/MolarityExtensions.cs deleted file mode 100644 index a33b9d1888..0000000000 --- a/UnitsNet/CustomCode/Extensions/MolarityExtensions.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace UnitsNet.CustomCode.Extensions -{ - public static class MolarityExtensions - { - public static Density ToDensity(this Molarity molarity, Mass molecularWeight) - { - return Molarity.ToDensity(molarity, molecularWeight); - } - } -} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Extensions/PowerRatioExtensions.cs b/UnitsNet/CustomCode/Extensions/PowerRatioExtensions.cs deleted file mode 100644 index 4012c78e1b..0000000000 --- a/UnitsNet/CustomCode/Extensions/PowerRatioExtensions.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace UnitsNet.CustomCode.Extensions -{ - /// - /// Extension methods for . - /// - public static class PowerRatioExtensions - { - /// - /// Gets a from a . - /// - /// - /// Provides a nicer syntax for converting a power ratio back to a power. - /// - /// var power = powerRatio.ToPower(); - /// - /// - public static Power ToPower(this PowerRatio powerRatio) - { - return PowerRatio.ToPower(powerRatio); - } - - /// - /// Gets a from a . - /// - /// The power ratio. - /// The input impedance of the load. This is usually 50, 75 or 600 ohms. - public static AmplitudeRatio ToAmplitudeRatio(this PowerRatio powerRatio, ElectricResistance impedance) - { - return PowerRatio.ToAmplitudeRatio(powerRatio, impedance); - } - } -} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Extensions/DensityExtensions.cs b/UnitsNet/CustomCode/GlobalConfiguration.cs similarity index 66% rename from UnitsNet/CustomCode/Extensions/DensityExtensions.cs rename to UnitsNet/CustomCode/GlobalConfiguration.cs index e0a6585758..396eb0ca07 100644 --- a/UnitsNet/CustomCode/Extensions/DensityExtensions.cs +++ b/UnitsNet/CustomCode/GlobalConfiguration.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,19 +19,24 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -namespace UnitsNet.CustomCode.Extensions +using System; +using System.Globalization; + +// ReSharper disable once CheckNamespace +namespace UnitsNet { - /// - /// Extension methods for . - /// - public static class DensityExtensions + public sealed class GlobalConfiguration { /// - /// Gets from . + /// 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. /// - public static Molarity ToMolarity(this Density density, Mass molecularWeight) - { - return Density.ToMolarity(density, molecularWeight); - } +#if WINDOWS_UWP + // Windows Runtime Component does not support exposing the IFormatProvider type in public API + internal +#else + public +#endif + static IFormatProvider DefaultCulture { get; set; } = CultureInfo.CurrentUICulture; } } diff --git a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs index 1470046b6a..d4f20f0030 100644 --- a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,6 +19,11 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +// ReSharper disable once CheckNamespace + +using System; +using UnitsNet.Units; + namespace UnitsNet { // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components @@ -32,6 +37,9 @@ public partial struct Acceleration { // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP + /// + /// Multiply and to get . + /// public static SpecificWeight operator *(Acceleration acceleration, Density density) { return new SpecificWeight(acceleration.MetersPerSecondSquared * density.KilogramsPerCubicMeter, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index 5933fbbf48..0e68fb595b 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -62,35 +62,43 @@ public partial struct AmplitudeRatio } /// - /// Gets an in decibels (dB) relative to 1 volt RMS from an - /// . + /// Gets an from this . /// - /// The voltage (electric potential) relative to one volt RMS. - public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage) + /// + /// Provides a nicer syntax for converting an amplitude ratio back to a voltage. + /// + /// var voltage = voltageRatio.ToElectricPotential(); + /// + /// + public ElectricPotential ToElectricPotential() { - return new AmplitudeRatio(voltage); + // E(V) = 1V * 10^(E(dBV)/20) + return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); } /// - /// Gets an from . + /// Converts this to a . /// - /// The voltage ratio to convert to voltage (electric potential). - public static ElectricPotential ToElectricPotential(AmplitudeRatio voltageRatio) + /// 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 ) { - // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts(Math.Pow(10, voltageRatio.DecibelVolts / 20)); + // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) + return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); } + #region Static Methods + /// - /// Converts a to a . + /// Gets an in decibels (dB) relative to 1 volt RMS from an + /// . /// - /// The amplitude ratio to convert. - /// 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 static PowerRatio ToPowerRatio(AmplitudeRatio amplitudeRatio, ElectricResistance impedance) + /// The voltage (electric potential) relative to one volt RMS. + public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage) { - // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts(amplitudeRatio.DecibelVolts - 10 * Math.Log10(impedance.Ohms / 1)); + return new AmplitudeRatio(voltage); } + + #endregion } } diff --git a/UnitsNet/CustomCode/Quantities/Angle.extra.cs b/UnitsNet/CustomCode/Quantities/Angle.extra.cs index fdcd60cbcb..68676d7e50 100644 --- a/UnitsNet/CustomCode/Quantities/Angle.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Angle.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -49,4 +46,4 @@ public partial struct Angle } #endif } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/Area.extra.cs b/UnitsNet/CustomCode/Quantities/Area.extra.cs index 1b7c5c5de4..f6fc2770c4 100644 --- a/UnitsNet/CustomCode/Quantities/Area.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Area.extra.cs @@ -19,6 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +using System; + // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -31,6 +33,21 @@ public sealed partial class Area public partial struct Area #endif { + #region Static Methods + + 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); + } + + #endregion + // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static Length operator /(Area area, Length length) @@ -47,16 +64,6 @@ public partial struct Area { return VolumeFlow.FromCubicMetersPerSecond(area.SquareMeters * speed.MetersPerSecond); } - - public static Area FromCircleDiameter(Length diameter) - { - return System.Math.PI * diameter * diameter / 4; - } - - public static Area FromCircleRadius(Length radius) - { - return System.Math.PI * radius * radius; - } #endif } } diff --git a/UnitsNet/CustomCode/Quantities/Density.extra.cs b/UnitsNet/CustomCode/Quantities/Density.extra.cs index d3ce59f41d..6fd11240ff 100644 --- a/UnitsNet/CustomCode/Quantities/Density.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Density.extra.cs @@ -19,6 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +using UnitsNet.Units; + // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -31,6 +33,17 @@ public sealed partial class Density public partial struct Density #endif { + /// + /// Gets from this . + /// + /// + public Molarity ToMolarity(Mass molecularWeight) + { + return Molarity.FromMolesPerCubicMeter(KilogramsPerCubicMeter / molecularWeight.Kilograms); + } + + #region Static Methods + /// /// Get from . /// @@ -38,13 +51,10 @@ public partial struct Density /// public static Density FromMolarity(Molarity molarity, Mass molecularWeight) { - return new Density(molarity.MolesPerCubicMeter * molecularWeight.Kilograms); + return new Density(molarity.MolesPerCubicMeter * molecularWeight.Kilograms, DensityUnit.KilogramPerCubicMeter); } - public static Molarity ToMolarity(Density density, Mass molecularWeight) - { - return Molarity.FromMolesPerCubicMeter(density.KilogramsPerCubicMeter / molecularWeight.Kilograms); - } + #endregion // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -70,7 +80,7 @@ public static Molarity ToMolarity(Density density, Mass molecularWeight) public static SpecificWeight operator *(Density density, Acceleration acceleration) { - return new SpecificWeight(density.KilogramsPerCubicMeter * acceleration.MetersPerSecondSquared, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); + return new SpecificWeight(density.KilogramsPerCubicMeter * acceleration.MetersPerSecondSquared, SpecificWeightUnit.NewtonPerCubicMeter); } #endif } diff --git a/UnitsNet/CustomCode/Quantities/Duration.extra.cs b/UnitsNet/CustomCode/Quantities/Duration.extra.cs index 9a6e8d21d5..5748f67250 100644 --- a/UnitsNet/CustomCode/Quantities/Duration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Duration.extra.cs @@ -33,6 +33,19 @@ public sealed partial class Duration public partial struct Duration #endif { + /// + /// 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 ); + } + // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static DateTime operator +(DateTime time, Duration duration) @@ -75,16 +88,6 @@ public static explicit operator Duration(TimeSpan duration) return duration.Seconds >= timeSpan.TotalSeconds; } - public static bool operator ==(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds == timeSpan.TotalSeconds; - } - - public static bool operator !=(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds != timeSpan.TotalSeconds; - } - public static bool operator <(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds < duration.Seconds; @@ -105,33 +108,10 @@ public static explicit operator Duration(TimeSpan duration) return timeSpan.TotalSeconds >= duration.Seconds; } - public static bool operator ==(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds == duration.Seconds; - } - - public static bool operator !=(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds != duration.Seconds; - } - public static Volume operator *(Duration duration, VolumeFlow volumeFlow) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * duration.Seconds); } #endif - - /// - /// 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/CustomCode/Extensions/ElectricPotentialExtensions.cs b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs similarity index 63% rename from UnitsNet/CustomCode/Extensions/ElectricPotentialExtensions.cs rename to UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs index b7d6433311..6f1fc43ea7 100644 --- a/UnitsNet/CustomCode/Extensions/ElectricPotentialExtensions.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs @@ -19,16 +19,23 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -namespace UnitsNet.CustomCode.Extensions +using System; +using UnitsNet.Units; + +// ReSharper disable once CheckNamespace +namespace UnitsNet { - /// - /// Extension methods for . - /// - public static class ElectricPotentialExtensions + // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components + // Public structures can't have any members other than public fields, and those fields must be value types or strings. + // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. +#if WINDOWS_UWP + public sealed partial class ElectricPotential +#else + public partial struct ElectricPotential +#endif { /// - /// Gets an in decibels (dB) relative to 1 volt RMS from an - /// . + /// 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). @@ -36,9 +43,9 @@ public static class ElectricPotentialExtensions /// var voltageRatio = voltage.ToAmplitudeRatio(); /// /// - public static AmplitudeRatio ToAmplitudeRatio(this ElectricPotential voltage) + public AmplitudeRatio ToAmplitudeRatio() { - return AmplitudeRatio.FromElectricPotential(voltage); + return AmplitudeRatio.FromElectricPotential(this); } } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/Force.extra.cs b/UnitsNet/CustomCode/Quantities/Force.extra.cs index 86b3ed0711..f13fd8cbcd 100644 --- a/UnitsNet/CustomCode/Quantities/Force.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Force.extra.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,6 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +using UnitsNet.Units; + // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -31,6 +33,17 @@ public sealed partial class Force public partial struct Force #endif { + 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); + } + // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static Power operator *(Force force, Speed speed) @@ -63,31 +76,5 @@ public partial struct Force return ForcePerLength.FromNewtonsPerMeter(force.Newtons / length.Meters); } #endif - - // Method overloads with same number of argumnets not supported in Universal Windows Platform (WinRT Components) -#if !WINDOWS_UWP - public static Force FromPressureByArea(Pressure p, Length2d area) - { - double metersSquared = area.Meters.X * area.Meters.Y; - double newtons = p.Pascals * metersSquared; - return new Force(newtons); - } - - public static Force FromMassByAcceleration(Mass mass, double metersPerSecondSquared) - { - return new Force(mass.Kilograms * metersPerSecondSquared); - } -#endif - - public static Force FromPressureByArea(Pressure p, Area area) - { - double newtons = p.Pascals * area.SquareMeters; - return new Force(newtons); - } - - public static Force FromMassByAcceleration(Mass mass, Acceleration acceleration) - { - return new Force(mass.Kilograms * acceleration.MetersPerSecondSquared); - } } } diff --git a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs index bc637de97e..72dbd14940 100644 --- a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -69,4 +66,4 @@ public partial struct KinematicViscosity } #endif } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs index 4395200509..ba34a2e828 100644 --- a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs +++ b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs @@ -35,14 +35,14 @@ public partial struct LapseRate #if !WINDOWS_UWP public static Length operator /(TemperatureDelta left, LapseRate right) { - return Length.FromKilometers(left.KelvinsDelta / right.DegreesCelciusPerKilometer); + return Length.FromKilometers(left.Kelvins / right.DegreesCelciusPerKilometer); } public static TemperatureDelta operator *(Length left, LapseRate right) => right * left; public static TemperatureDelta operator *(LapseRate left, Length right) { - return TemperatureDelta.FromDegreesCelsiusDelta(left.DegreesCelciusPerKilometer * right.Kilometers); + return TemperatureDelta.FromDegreesCelsius(left.DegreesCelciusPerKilometer * right.Kilometers); } #endif } diff --git a/UnitsNet/CustomCode/Quantities/Length.extra.cs b/UnitsNet/CustomCode/Quantities/Length.extra.cs index e33d5e462e..7d9ba655d8 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ // THE SOFTWARE. using System; +using System.Text.RegularExpressions; using JetBrains.Annotations; using UnitsNet.Units; @@ -68,6 +69,76 @@ public static Length FromFeetInches(double feet, double inches) // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP + + /// + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) + /// + /// + /// 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) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + if (!TryParseFeetInches(str, out Length result, formatProvider)) + { + // A bit lazy, but I didn't want to duplicate this edge case implementation just to get more narrow exception descriptions. + throw new FormatException("Unable to parse feet and inches. Expected format \"2' 4\"\" or \"2 ft 4 in\". Whitespace is optional."); + } + + return result; + } + + /// + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) + /// + /// + /// Parsed length. + /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. + public static bool TryParseFeetInches([CanBeNull] string str, out Length result, IFormatProvider formatProvider = null) + { + if (str == null) + { + result = default; + return false; + } + + str = str.Trim(); + + // This succeeds if only feet or inches are given, not both + if (TryParse(str, formatProvider, out result)) + return true; + + var quantityParser = QuantityParser.Default; + string footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, matchEntireString: false); + string inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, matchEntireString: false); + + // Match entire string exactly + string pattern = $@"^(?{footRegex})\s?(?{inchRegex})$"; + + var match = new Regex(pattern, RegexOptions.Singleline).Match(str); + if (!match.Success) return false; + + var feetGroup = match.Groups["feet"]; + var inchesGroup = match.Groups["inches"]; + if (TryParse(feetGroup.Value, formatProvider, out Length feet) && + TryParse(inchesGroup.Value, formatProvider, out Length inches)) + { + result = feet + inches; + return true; + } + + result = default; + return false; + } + public static Speed operator /(Length length, TimeSpan timeSpan) { return Speed.FromMetersPerSecond(length.Meters/timeSpan.TotalSeconds); @@ -140,11 +211,10 @@ public string ToString([CanBeNull] Culture 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 unitSystem = UnitSystem.GetCached(cultureInfo); - var footUnit = unitSystem.GetDefaultAbbreviation(LengthUnit.Foot); - var inchUnit = unitSystem.GetDefaultAbbreviation(LengthUnit.Inch); + var footUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Foot); + var inchUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Inch); - return string.Format(unitSystem.Culture, "{0:n0} {1} {2:n0} {3}", Feet, footUnit, Math.Round(Inches), + return string.Format(GlobalConfiguration.DefaultCulture, "{0:n0} {1} {2:n0} {3}", Feet, footUnit, Math.Round(Inches), inchUnit); } } diff --git a/UnitsNet/CustomCode/Quantities/Level.extra.cs b/UnitsNet/CustomCode/Quantities/Level.extra.cs index 5162e49992..b222bbcaf6 100644 --- a/UnitsNet/CustomCode/Quantities/Level.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Level.extra.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,10 +44,12 @@ public Level(double quantity, double reference) string errorMessage = $"The base-10 logarithm of a number ≤ 0 is undefined ({quantity}/{reference})."; - if ((quantity == 0) || ((quantity < 0) && (reference > 0))) + // ReSharper disable CompareOfFloatsByEqualityOperator + if (quantity == 0 || quantity < 0 && reference > 0) throw new ArgumentOutOfRangeException(nameof(quantity), errorMessage); - if ((reference == 0) || ((quantity > 0) && (reference < 0))) + if (reference == 0 || quantity > 0 && reference < 0) throw new ArgumentOutOfRangeException(nameof(reference), errorMessage); + // ReSharper restore CompareOfFloatsByEqualityOperator _value = 10*Math.Log10(quantity/reference); _unit = LevelUnit.Decibel; diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 36978514c0..11fb195c63 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -43,7 +43,7 @@ public partial struct Mass { public static Mass FromGravitationalForce(Force f) { - return new Mass(f.KilogramsForce); + return new Mass(f.KilogramsForce, MassUnit.Kilogram); } /// @@ -131,11 +131,10 @@ public string ToString([CanBeNull] Culture 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 unitSystem = UnitSystem.GetCached(cultureInfo); - var stoneUnit = unitSystem.GetDefaultAbbreviation(MassUnit.Stone); - var poundUnit = unitSystem.GetDefaultAbbreviation(MassUnit.Pound); + var stoneUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Stone); + var poundUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Pound); - return string.Format(unitSystem.Culture, "{0:n0} {1} {2:n0} {3}", + return string.Format(GlobalConfiguration.DefaultCulture, "{0:n0} {1} {2:n0} {3}", Stone, stoneUnit, Math.Round(Pounds), poundUnit); } } diff --git a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs index 9bbdac03b3..49288cfe60 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { diff --git a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs index a34a1a026d..9226caed22 100644 --- a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs @@ -26,24 +26,26 @@ public partial struct Molarity } /// - /// Get from . + /// Get a from this . /// - /// /// - public static Molarity FromDensity(Density density, Mass molecularWeight) + public Density ToDensity(Mass molecularWeight) { - return new Molarity(density, molecularWeight); + return Density.FromKilogramsPerCubicMeter(MolesPerCubicMeter * molecularWeight.Kilograms); } + #region Static Methods + /// - /// Get from . + /// Get from . /// - /// + /// /// - /// - public static Density ToDensity(Molarity molarity, Mass molecularWeight) + public static Molarity FromDensity(Density density, Mass molecularWeight) { - return Density.FromKilogramsPerCubicMeter(molarity.MolesPerCubicMeter * molecularWeight.Kilograms); + return new Molarity(density, molecularWeight); } + + #endregion } } diff --git a/UnitsNet/CustomCode/Quantities/Power.extra.cs b/UnitsNet/CustomCode/Quantities/Power.extra.cs index 5db0ad8aa1..77b1616860 100644 --- a/UnitsNet/CustomCode/Quantities/Power.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Power.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -36,6 +33,20 @@ public sealed partial class Power public partial struct Power #endif { + /// + /// 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); + } + // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static Energy operator *(Power power, TimeSpan time) diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index a0b00e0d9a..4180da4d89 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -58,34 +58,41 @@ public partial struct PowerRatio } /// - /// Gets a from a relative to one watt. + /// Gets a from this (which is a power level relative to one watt). /// - /// The power relative to one watt. - public static PowerRatio FromPower(Power power) + /// + /// Provides a nicer syntax for converting a power ratio back to a power. + /// + /// var power = powerRatio.ToPower(); + /// + /// + public Power ToPower() { - return new PowerRatio(power); + // P(W) = 1W * 10^(P(dBW)/10) + return Power.FromWatts(Math.Pow(10, DecibelWatts / 10)); } /// - /// Gets a from a (which is a power level relative to one watt). + /// Gets a from this . /// - /// The power level relative to one watt. - public static Power ToPower(PowerRatio powerRatio) + /// The input impedance of the load. This is usually 50, 75 or 600 ohms. + public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance) { - // P(W) = 1W * 10^(P(dBW)/10) - return Power.FromWatts(Math.Pow(10, powerRatio.DecibelWatts / 10)); + // 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 . + /// Gets a from a relative to one watt. /// - /// The power ratio. - /// 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 static AmplitudeRatio ToAmplitudeRatio(PowerRatio powerRatio, ElectricResistance impedance) + /// The power relative to one watt. + public static PowerRatio FromPower(Power power) { - // E(dBV) = 10*log10(Z(Ω)/1) + P(dBW) - return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10(impedance.Ohms / 1) + powerRatio.DecibelWatts); + return new PowerRatio(power); } + + #endregion } } diff --git a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs index 5282a13ee0..0afa95479d 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { @@ -59,4 +56,4 @@ public partial struct RotationalSpeed } #endif } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs index 50207c0bf6..b9403d2107 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,6 +19,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +// 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 diff --git a/UnitsNet/CustomCode/Quantities/Speed.extra.cs b/UnitsNet/CustomCode/Quantities/Speed.extra.cs index f27bd4d765..8e5eaab04d 100644 --- a/UnitsNet/CustomCode/Quantities/Speed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Speed.extra.cs @@ -19,11 +19,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#if !WINDOWS_UWP using System; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet { diff --git a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index 6f422283ce..fed00fd718 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -42,7 +42,7 @@ public partial struct Temperature /// The new temperature. public static Temperature operator +(Temperature left, TemperatureDelta right) { - return new Temperature(left.Kelvins + right.KelvinsDelta); + return new Temperature(left.Kelvins + right.Kelvins, TemperatureUnit.Kelvin); } /// @@ -52,7 +52,7 @@ public partial struct Temperature /// The new temperature. public static Temperature operator +(TemperatureDelta left, Temperature right) { - return new Temperature(left.KelvinsDelta + right.Kelvins); + return new Temperature(left.Kelvins + right.Kelvins, TemperatureUnit.Kelvin); } /// @@ -62,7 +62,7 @@ public partial struct Temperature /// The new temperature. public static Temperature operator -(Temperature left, TemperatureDelta right) { - return new Temperature(left.Kelvins - right.KelvinsDelta); + return new Temperature(left.Kelvins - right.Kelvins, TemperatureUnit.Kelvin); } /// @@ -72,7 +72,7 @@ public partial struct Temperature /// The delta temperature (difference). public static TemperatureDelta operator -(Temperature left, Temperature right) { - return new TemperatureDelta(left.Kelvins - right.Kelvins); + return new TemperatureDelta(left.Kelvins - right.Kelvins, TemperatureDeltaUnit.Kelvin); } #endif @@ -111,4 +111,4 @@ public Temperature Divide(double divisor, TemperatureUnit unit) return From(resultInUnit, unit); } } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs index 88d598e747..4ec7201483 100644 --- a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs +++ b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs @@ -35,7 +35,7 @@ public partial struct TemperatureDelta #if !WINDOWS_UWP public static LapseRate operator /(TemperatureDelta left, Length right) { - return LapseRate.FromDegreesCelciusPerKilometer(left.DegreesCelsiusDelta / right.Kilometers); + return LapseRate.FromDegreesCelciusPerKilometer(left.DegreesCelsius / right.Kilometers); } public static SpecificEnergy operator *(SpecificEntropy specificEntropy, TemperatureDelta temperatureDelta) diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index 7835bf8b72..d6bedd5c92 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,104 +30,191 @@ // ReSharper disable once CheckNamespace namespace UnitsNet { - internal delegate TQuantity ParseUnit(string value, string unit, IFormatProvider formatProvider = null); - internal static class QuantityParser +#if !WINDOWS_UWP + internal delegate TQuantity QuantityFromDelegate(QuantityValue value, TUnitType fromUnit) + where TQuantity : IQuantity + where TUnitType : Enum; +#else + internal delegate TQuantity QuantityFromDelegate(double value, TUnitType fromUnit) + where TQuantity : IQuantity + where TUnitType : Enum; +#endif + + 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 static TQuantity Parse([NotNull] string str, + internal TQuantity Parse([NotNull] string str, [CanBeNull] IFormatProvider formatProvider, - [NotNull] ParseUnit parseUnit, - [NotNull] Func add) + [NotNull] QuantityFromDelegate fromDelegate) + where TQuantity : IQuantity + where TUnitType : Enum { if (str == null) throw new ArgumentNullException(nameof(str)); - if (parseUnit == null) throw new ArgumentNullException(nameof(parseUnit)); - if (add == null) throw new ArgumentNullException(nameof(add)); + str = str.Trim(); - NumberFormatInfo numFormat = formatProvider != null + var numFormat = formatProvider != null ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) : NumberFormatInfo.CurrentInfo; - string numRegex = string.Format(@"[\d., {0}{1}]*\d", - // allows digits, dots, commas, and spaces in the quantity (must end in digit) - numFormat.NumberGroupSeparator, // adds provided (or current) culture's group separator - numFormat.NumberDecimalSeparator); // adds provided (or current) culture's decimal separator + if (numFormat == null) + throw new InvalidOperationException($"No number format was found for the given format provider: {formatProvider}"); - const string exponentialRegex = @"(?:[eE][-+]?\d+)?)"; + var regex = CreateRegexForQuantity(formatProvider); - string[] unitAbbreviations = UnitSystem.GetCached(formatProvider) - .GetAllAbbreviations(typeof(TUnitType)) - .OrderByDescending(s => s.Length) // Important to order by length -- if "m" is before "mm" and the input is "mm", it will match just "m" and throw invalid string error - .Select(Regex.Escape) // Escape special regex characters - .ToArray(); - - string unitsRegex = $"({String.Join("|", unitAbbreviations)})"; - - string regexString = string.Format(@"(?:\s*(?[-+]?{0}{1}{2}{3})?{4}{5}", - numRegex, // capture base (integral) Quantity value - exponentialRegex, // capture exponential (if any), end of Quantity capturing - @"\s?", // ignore whitespace (allows both "1kg", "1 kg") - $@"(?{unitsRegex})", // capture Unit by list of abbreviations - @"(and)?,?", // allow "and" & "," separators between quantities - @"(?[a-z]*)?"); // capture invalid input - - List quantities = ParseWithRegex(regexString, str, parseUnit, formatProvider); - if (quantities.Count == 0) + if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) { - throw new ArgumentException( - "Expected string to have at least one pair of quantity and unit in the format" - + " \"<quantity> <unit>\". Eg. \"5.5 m\" or \"1ft 2in\""); + 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 quantities.Aggregate(add); + + 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); + } + + 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 static List ParseWithRegex(string regexString, string str, ParseUnit parseUnit, - IFormatProvider formatProvider = null) + private TQuantity ParseWithRegex(string valueString, + string unitString, + QuantityFromDelegate fromDelegate, + IFormatProvider formatProvider) + where TQuantity : IQuantity + where TUnitType : Enum { - var regex = new Regex(regexString); - MatchCollection matches = regex.Matches(str.Trim()); - var converted = new List(); + 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; - foreach (Match match in matches) + 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) { - GroupCollection groups = match.Groups; - - string valueString = groups["value"].Value; - string unitString = groups["unit"].Value; - if (groups["invalid"].Value != "") - { - var newEx = new UnitsNetException("Invalid string detected: " + groups["invalid"].Value); - newEx.Data["input"] = str; - newEx.Data["matched value"] = valueString; - newEx.Data["matched unit"] = unitString; - newEx.Data["formatprovider"] = formatProvider?.ToString(); - throw newEx; - } - if ((valueString == "") && (unitString == "")) continue; - - try - { - converted.Add(parseUnit(valueString, unitString, formatProvider)); - } - catch (AmbiguousUnitParseException) - { - throw; - } - catch (Exception ex) - { - var newEx = new UnitsNetException("Error parsing string.", ex); - newEx.Data["input"] = str; - newEx.Data["matched value"] = valueString; - newEx.Data["matched unit"] = unitString; - newEx.Data["formatprovider"] = formatProvider?.ToString(); - throw newEx; - } + valueString = null; + unitString = null; + return false; } - return converted; + + 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/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs new file mode 100644 index 0000000000..890fa74658 --- /dev/null +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -0,0 +1,317 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using JetBrains.Annotations; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +using UnitTypeToLookup = System.Collections.Generic.Dictionary; + +// ReSharper disable once CheckNamespace +namespace UnitsNet +{ + public sealed partial 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 localization in GeneratedLocalizations) + { + var culture = new CultureInfo(localization.CultureName); + MapUnitToAbbreviation(localization.UnitType, localization.UnitValue, culture, localization.UnitAbbreviations); + } + } + + /// + /// 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. + /// Unit abbreviations to add. + /// The type of unit enum. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + void MapUnitToAbbreviation(TUnitType unit, params string[] abbreviations) where TUnitType : Enum + { + MapUnitToAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), GlobalConfiguration.DefaultCulture, abbreviations); + } + + /// + /// 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. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + void MapUnitToAbbreviation(TUnitType unit, IFormatProvider formatProvider, params string[] abbreviations) where TUnitType : Enum + { + // Assuming TUnitType is an enum, this conversion is safe. Seems not possible to enforce this today. + // Src: http://stackoverflow.com/questions/908543/how-to-convert-from-system-enum-to-base-integer + // http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum + var unitValue = Convert.ToInt32(unit); + var unitType = typeof(TUnitType); + + MapUnitToAbbreviation(unitType, unitValue, formatProvider, abbreviations); + } + + /// + /// 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 type. + /// The unit enum value. + /// The format provider to use for lookup. Defaults to if null. + /// Unit abbreviations to add. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] params string[] abbreviations) + { + if (!unitType.IsEnum()) + throw new ArgumentException("Must be an enum type.", nameof(unitType)); + + if (abbreviations == null) + throw new ArgumentNullException(nameof(abbreviations)); + + formatProvider = formatProvider ?? GlobalConfiguration.DefaultCulture; + + if(!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) + quantitiesForProvider = _lookupsForCulture[formatProvider] = new UnitTypeToLookup(); + + if(!quantitiesForProvider.TryGetValue(unitType, out var unitToAbbreviations)) + unitToAbbreviations = quantitiesForProvider[unitType] = new UnitValueAbbreviationLookup(); + + foreach(var abbr in abbreviations) + { + unitToAbbreviations.Add(unitValue, abbr); + } + } + + /// + /// 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. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + 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/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs new file mode 100644 index 0000000000..97d4bffda4 --- /dev/null +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -0,0 +1,213 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Linq; +using JetBrains.Annotations; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +// ReSharper disable once CheckNamespace +namespace UnitsNet +{ + 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. + /// + /// + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + object 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); + + switch (unitIntValues.Count) + { + case 1: + return 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. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods +#if WINDOWS_UWP + internal +#else + public +#endif + 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. + [PublicAPI] + public bool TryParse(string unitAbbreviation, Type unitType, out object 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. + [PublicAPI] +#if WINDOWS_UWP + internal +#else + public +#endif + bool TryParse(string unitAbbreviation, Type unitType, [CanBeNull] IFormatProvider formatProvider, out object unit) + { + if (unitAbbreviation == null) + { + unit = default; + return false; + } + + unitAbbreviation = unitAbbreviation.Trim(); + unit = GetDefault(unitType); + + if(!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + return false; + + var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation); + if(unitIntValues.Count != 1) + return false; + + unit = unitIntValues[0]; + return true; + } + + /// + /// Get default(Type) of + /// + /// . + /// Null for reference types, 0 for numeric types and default constructor for the rest. + /// + private static object GetDefault(Type type) + { + return type.IsValueType() ? Activator.CreateInstance(type): null; + } + } +} diff --git a/UnitsNet/CustomCode/UnitSystem.cs b/UnitsNet/CustomCode/UnitSystem.cs deleted file mode 100644 index ce253110bc..0000000000 --- a/UnitsNet/CustomCode/UnitSystem.cs +++ /dev/null @@ -1,536 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.I18n; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - [PublicAPI] - public sealed partial class UnitSystem - { - private static readonly Dictionary CultureToInstance; - - /// - /// Fallback culture used by and - /// - /// if no abbreviations are found with current . - /// - /// - /// 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"); - - private static readonly object LockUnitSystemCache = new object(); - - /// - /// Per-unit-type dictionary of enum values by abbreviation. This is the inverse of - /// . - /// - private readonly Dictionary _unitTypeToAbbrevToUnitValue; - - /// - /// Per-unit-type dictionary of abbreviations by enum value. This is the inverse of - /// . - /// - private readonly Dictionary>> _unitTypeToUnitValueToAbbrevs; - - /// - /// The culture of which this unit system is based on. Either passed in to constructor or the default culture. - /// - [NotNull] [PublicAPI] internal readonly IFormatProvider Culture; - - static UnitSystem() - { - CultureToInstance = new Dictionary(); - Default = GetCached((CultureInfo) null); - } - - /// - /// Create unit system for parsing and generating strings with the English US culture. - /// - public UnitSystem() : this(DefaultCulture) - { - - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - /// - /// Create unit system for parsing and generating strings of the specified culture. - /// If null is specified, the default English US culture will be used. - /// - /// - public UnitSystem([CanBeNull] string cultureInfo) : this(cultureInfo != null ? new CultureInfo(cultureInfo) : DefaultCulture) - { - } -#else - /// - /// Create unit system for parsing and generating strings of the specified culture. - /// If null is specified, the default English US culture will be used. - /// - /// - /// - /// If true (default), loads abbreviations per unit defined in - /// /UnitsNet/UnitDefinitions/*.json files. Otherwise, creates an empty instance. - /// - public UnitSystem([CanBeNull] string cultureInfo, bool loadDefaultAbbreviations = true) : this(cultureInfo != null ? new CultureInfo(cultureInfo) : DefaultCulture) - { - } -#endif - - /// - /// Create unit system for parsing and generating strings of the specified culture. - /// If null is specified, the default English US culture will be used. - /// - /// - /// - /// If true (default), loads abbreviations per unit defined in - /// /UnitsNet/UnitDefinitions/*.json files. Otherwise, creates an empty instance. - /// - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - UnitSystem([CanBeNull] IFormatProvider cultureInfo, bool loadDefaultAbbreviations = true) - { - if (cultureInfo == null) - cultureInfo = DefaultCulture; - - Culture = cultureInfo; - _unitTypeToUnitValueToAbbrevs = new Dictionary>>(); - _unitTypeToAbbrevToUnitValue = new Dictionary(); - - if (loadDefaultAbbreviations) - LoadDefaultAbbreviations(cultureInfo); - } - - /// - /// 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. - /// -#if WINDOWS_UWP - // Windows Runtime Component does not support exposing the IFormatProvider type in public API - internal -#else - public -#endif - static IFormatProvider DefaultCulture { get; set; } = CultureInfo.CurrentUICulture; - - public bool IsFallbackCulture => Culture.Equals(FallbackCulture); - - [PublicAPI] - public static void ClearCache() - { - lock (LockUnitSystemCache) - { - CultureToInstance.Clear(); - } - } - - /// - /// The default singleton instance based on the system default UI culture . - /// This instance is used internally for all parsing and string formatting where culture is not explicitly specified, - /// so use this if you want extend with new units via - /// and make the new units available to methods like ; when culture is not - /// explicitly - /// specified. - /// If you do explicitly specify culture when parsing and calling ToString(), then just make sure to call - /// with the same culture. - /// - public static UnitSystem Default { get; } - - /// - /// Get or create a unit system for parsing and presenting numbers, units and abbreviations. - /// Creating can be a little expensive, so it will use a static cache. - /// To always create, use the constructor. - /// - /// - [PublicAPI] - [Obsolete("Use Default property instead. This will be removed in the future.")] - public static UnitSystem GetCached() - { - return GetCached((CultureInfo) null); - } - - /// - /// Get or create a unit system for parsing and presenting numbers, units and abbreviations. - /// Creating can be a little expensive, so it will use a static cache. - /// To always create, use the constructor. - /// - /// Culture to use. If null then will be used. - /// - [PublicAPI] - public static UnitSystem GetCached([CanBeNull] string cultureName) - { - IFormatProvider cultureInfo = cultureName == null ? DefaultCulture : new CultureInfo(cultureName); - return GetCached(cultureInfo); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - static UnitSystem GetCached([CanBeNull] IFormatProvider cultureInfo) - { - if (cultureInfo == null) - cultureInfo = DefaultCulture; - - lock (LockUnitSystemCache) - { - if (CultureToInstance.ContainsKey(cultureInfo)) - return CultureToInstance[cultureInfo]; - - CultureToInstance[cultureInfo] = new UnitSystem(cultureInfo); - return CultureToInstance[cultureInfo]; - } - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - static TUnitType Parse(string unitAbbreviation, IFormatProvider culture) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - return GetCached(culture).Parse(unitAbbreviation); - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - TUnitType Parse(string unitAbbreviation) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - 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 . - /// Unit enum value, such as . - /// No units match the abbreviation. - /// More than one unit matches the abbrevation. - [PublicAPI] - public object Parse(string unitAbbreviation, Type unitType) - { - AbbreviationMap abbrevToUnitValue; - if (!_unitTypeToAbbrevToUnitValue.TryGetValue(unitType, out abbrevToUnitValue)) - throw new UnitNotFoundException($"No abbreviations defined for unit type [{unitType}] for culture [{Culture}]."); - - List unitIntValues; - List unitValues = abbrevToUnitValue.TryGetValue(unitAbbreviation, out unitIntValues) - ? unitIntValues.Distinct().Cast().ToList() - : new List(); - - switch (unitValues.Count) - { - case 1: - return unitValues[0]; - case 0: - throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{unitType}]."); - default: - string unitsCsv = string.Join(", ", unitValues.Select(x => Enum.GetName(unitType, x)).ToArray()); - throw new AmbiguousUnitParseException( - $"Cannot parse \"{unitAbbreviation}\" since it could be either of these: {unitsCsv}"); - } - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - static string GetDefaultAbbreviation(TUnitType unit, CultureInfo culture) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - return GetCached(culture).GetDefaultAbbreviation(unit); - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - string GetDefaultAbbreviation(TUnitType unit) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - return GetAllAbbreviations(unit).First(); - } - - [PublicAPI] - public string GetDefaultAbbreviation(Type unitType, int unitValue) - { - return GetAllAbbreviations(unitType, unitValue).First(); - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - void MapUnitToAbbreviation(TUnitType unit, params string[] abbreviations) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - // Assuming TUnitType is an enum, this conversion is safe. Seems not possible to enforce this today. - // Src: http://stackoverflow.com/questions/908543/how-to-convert-from-system-enum-to-base-integer - // http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum - int unitValue = Convert.ToInt32(unit); - Type unitType = typeof(TUnitType); - MapUnitToAbbreviation(unitType, unitValue, abbreviations); - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - void MapUnitToAbbreviation(Type unitType, int unitValue, [NotNull] params string[] abbreviations) - { - if (!unitType.IsEnum()) - throw new ArgumentException("Must be an enum type.", nameof(unitType)); - - if (abbreviations == null) - throw new ArgumentNullException(nameof(abbreviations)); - - Dictionary> unitValueToAbbrev; - if (!_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrev)) - { - unitValueToAbbrev = _unitTypeToUnitValueToAbbrevs[unitType] = new Dictionary>(); - } - - List existingAbbreviations; - if (!unitValueToAbbrev.TryGetValue(unitValue, out existingAbbreviations)) - { - existingAbbreviations = unitValueToAbbrev[unitValue] = new List(); - } - - // Append new abbreviations to any existing abbreviations so that we don't - // change the result of GetDefaultAbbreviation() if already defined. - unitValueToAbbrev[unitValue] = existingAbbreviations.Concat(abbreviations).Distinct().ToList(); - foreach (string abbreviation in abbreviations) - { - AbbreviationMap abbrevToUnitValue; - if (!_unitTypeToAbbrevToUnitValue.TryGetValue(unitType, out abbrevToUnitValue)) - { - abbrevToUnitValue = _unitTypeToAbbrevToUnitValue[unitType] = new AbbreviationMap(); - } - - if (!abbrevToUnitValue.ContainsKey(abbreviation)) - { - abbrevToUnitValue[abbreviation] = new List(); - } - abbrevToUnitValue[abbreviation].Add(unitValue); - } - } - - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - bool TryParse(string unitAbbreviation, out TUnitType unit) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - try - { - unit = (TUnitType) Parse(unitAbbreviation, typeof(TUnitType)); - return true; - } - catch - { - unit = default(TUnitType); - return false; - } - } - - [PublicAPI] - public bool TryParse(string unitAbbreviation, Type unitType, out object unit) - { - try - { - unit = Parse(unitAbbreviation, unitType); - return true; - } - catch - { - unit = GetDefault(unitType); - return false; - } - } - - /// - /// Get all abbreviations for unit. - /// - /// Enum type for units. - /// Enum value for unit. - /// Unit abbreviations associated with unit. - [PublicAPI] - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - string[] GetAllAbbreviations(TUnitType unit) - where TUnitType : /*Enum constraint hack*/ struct, IComparable, IFormattable - { - Dictionary> unitValueToAbbrevs; - List abbrevs; - - if (_unitTypeToUnitValueToAbbrevs.TryGetValue(typeof(TUnitType), out unitValueToAbbrevs) && - unitValueToAbbrevs.TryGetValue((int) (object) unit, out abbrevs)) - { - return abbrevs.ToArray(); - } - - return IsFallbackCulture - ? new[] {$"(no abbreviation for {typeof(TUnitType).Name}.{unit})"} - : GetCached(FallbackCulture).GetAllAbbreviations(unit); - } - - /// - /// Get all abbreviations for unit. - /// - /// Enum type for unit. - /// Enum value for unit. - /// Unit abbreviations associated with unit. - [PublicAPI] - public string[] GetAllAbbreviations(Type unitType, int unitValue) - { - Dictionary> unitValueToAbbrevs; - List abbrevs; - - if (_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrevs) && - unitValueToAbbrevs.TryGetValue(unitValue, out abbrevs)) - { - return abbrevs.ToArray(); - } - - // Fall back to default culture - return IsFallbackCulture - ? new[] {$"(no abbreviation for {unitType.Name} with numeric value {unitValue})"} - : GetCached(FallbackCulture).GetAllAbbreviations(unitType, unitValue); - } - - /// - /// Get all abbreviations for unit. - /// - /// Enum type for unit. - /// Unit abbreviations associated with unit. - [PublicAPI] - public string[] GetAllAbbreviations(Type unitType) - { - Dictionary> unitValueToAbbrevs; - if (_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrevs)) - { - return unitValueToAbbrevs.Values.SelectMany(x => x).ToArray(); - } - - // Fall back to default culture - return IsFallbackCulture - ? new[] {$"(no abbreviations for {unitType.Name})"} - : GetCached(FallbackCulture).GetAllAbbreviations(unitType); - } - - private void LoadDefaultAbbreviations([NotNull] IFormatProvider culture) - { - foreach (UnitLocalization localization in DefaultLocalizations) - { - Type unitEnumType = localization.UnitEnumType; - - foreach (CulturesForEnumValue ev in localization.EnumValues) - { - int unitEnumValue = ev.Value; - var usCulture = new CultureInfo("en-US"); - - // Fall back to US English if localization not found - AbbreviationsForCulture matchingCulture = - ev.Cultures.FirstOrDefault(a => a.Cult.Equals(culture)) ?? - ev.Cultures.FirstOrDefault(a => a.Cult.Equals(usCulture)); - - if (matchingCulture == null) - continue; - - MapUnitToAbbreviation(unitEnumType, unitEnumValue, matchingCulture.Abbreviations.ToArray()); - } - } - } - - /// - /// Avoids having too many nested generics for code clarity - /// - private class AbbreviationMap : Dictionary> - { - } - - /// - /// Get default(Type) of - /// - /// . - /// Null for reference types, 0 for numeric types and default constructor for the rest. - /// - private static object GetDefault(Type type) - { - return type - .IsValueType() - ? Activator.CreateInstance(type) - : null; - } - } -} diff --git a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs new file mode 100644 index 0000000000..18b8e8c171 --- /dev/null +++ b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs @@ -0,0 +1,84 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +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 UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); + private AbbreviationToUnitMap abbreviationToUnitMap = new AbbreviationToUnitMap(); + + internal UnitValueAbbreviationLookup() + { + unitToAbbreviationMap = new UnitToAbbreviationMap(); + abbreviationToUnitMap = 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) + { + if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var units)) + abbreviationToUnitMap[abbreviation] = units = new List(); + + return units.Distinct().ToList(); + } + + internal void Add(int unit, string abbreviation) + { + if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) + abbreviationsForUnit = unitToAbbreviationMap[unit] = new List(); + + if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) + abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); + + abbreviationsForUnit.Add(abbreviation); + unitsForAbbreviation.Add(unit); + } + } +} diff --git a/UnitsNet/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensions.cs b/UnitsNet/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensions.cs deleted file mode 100644 index 105ab5df8a..0000000000 --- a/UnitsNet/Extensions/NumberToTimeSpan/NumberToTimeSpanExtensions.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if !WINDOWS_UWP -// Extension methods/overloads not supported in Universal Windows Platform (WinRT Components) -using System; - -namespace UnitsNet.Extensions.NumberToTimeSpan -{ - public static class NumberToTimeSpanExtensions - { - // ReSharper disable InconsistentNaming - /// Shorthand for . - public static TimeSpan d(this int days) => TimeSpan.FromDays(days); - - /// Shorthand for . - public static TimeSpan d(this long days) => TimeSpan.FromDays(days); - - /// Shorthand for . - public static TimeSpan d(this float days) => TimeSpan.FromDays(days); - - /// Shorthand for . - public static TimeSpan d(this double days) => TimeSpan.FromDays(days); - - /// Shorthand for . - public static TimeSpan d(this decimal days) => TimeSpan.FromDays(Convert.ToDouble(days)); - - /// Shorthand for . - public static TimeSpan h(this int hours) => TimeSpan.FromHours(hours); - - /// Shorthand for . - public static TimeSpan h(this long hours) => TimeSpan.FromHours(hours); - - /// Shorthand for . - public static TimeSpan h(this float hours) => TimeSpan.FromHours(hours); - - /// Shorthand for . - public static TimeSpan h(this double hours) => TimeSpan.FromHours(hours); - - /// Shorthand for . - public static TimeSpan h(this decimal hours) => TimeSpan.FromHours(Convert.ToDouble(hours)); - - /// Shorthand for . - public static TimeSpan m(this int minutes) => TimeSpan.FromMinutes(minutes); - - /// Shorthand for . - public static TimeSpan m(this long minutes) => TimeSpan.FromMinutes(minutes); - - /// Shorthand for . - public static TimeSpan m(this float minutes) => TimeSpan.FromMinutes(minutes); - - /// Shorthand for . - public static TimeSpan m(this double minutes) => TimeSpan.FromMinutes(minutes); - - /// Shorthand for . - public static TimeSpan m(this decimal minutes) => TimeSpan.FromMinutes(Convert.ToDouble(minutes)); - - /// Shorthand for . - public static TimeSpan s(this int seconds) => TimeSpan.FromSeconds(seconds); - - /// Shorthand for . - public static TimeSpan s(this long seconds) => TimeSpan.FromSeconds(seconds); - - /// Shorthand for . - public static TimeSpan s(this float seconds) => TimeSpan.FromSeconds(seconds); - - /// Shorthand for . - public static TimeSpan s(this double seconds) => TimeSpan.FromSeconds(seconds); - - /// Shorthand for . - public static TimeSpan s(this decimal seconds) => TimeSpan.FromSeconds(Convert.ToDouble(seconds)); - - /// Shorthand for . - public static TimeSpan ms(this int milliseconds) => TimeSpan.FromMilliseconds(milliseconds); - - /// Shorthand for . - public static TimeSpan ms(this long milliseconds) => TimeSpan.FromMilliseconds(milliseconds); - - /// Shorthand for . - public static TimeSpan ms(this float milliseconds) => TimeSpan.FromMilliseconds(milliseconds); - - /// Shorthand for . - public static TimeSpan ms(this double milliseconds) => TimeSpan.FromMilliseconds(milliseconds); - - /// Shorthand for . - public static TimeSpan ms(this decimal milliseconds) => TimeSpan.FromMilliseconds(Convert.ToDouble(milliseconds)); - - // ReSharper restore InconsistentNaming - } -} - -#endif \ No newline at end of file diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAccelerationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAccelerationExtensions.g.cs deleted file mode 100644 index 9fc9b9cc5b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAccelerationExtensions.g.cs +++ /dev/null @@ -1,192 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAcceleration -{ - public static class NumberToAccelerationExtensions - { - #region CentimeterPerSecondSquared - - /// - public static Acceleration CentimetersPerSecondSquared(this T value) => Acceleration.FromCentimetersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? CentimetersPerSecondSquared(this T? value) where T : struct => Acceleration.FromCentimetersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecimeterPerSecondSquared - - /// - public static Acceleration DecimetersPerSecondSquared(this T value) => Acceleration.FromDecimetersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? DecimetersPerSecondSquared(this T? value) where T : struct => Acceleration.FromDecimetersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootPerSecondSquared - - /// - public static Acceleration FeetPerSecondSquared(this T value) => Acceleration.FromFeetPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? FeetPerSecondSquared(this T? value) where T : struct => Acceleration.FromFeetPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchPerSecondSquared - - /// - public static Acceleration InchesPerSecondSquared(this T value) => Acceleration.FromInchesPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? InchesPerSecondSquared(this T? value) where T : struct => Acceleration.FromInchesPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilometerPerSecondSquared - - /// - public static Acceleration KilometersPerSecondSquared(this T value) => Acceleration.FromKilometersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? KilometersPerSecondSquared(this T? value) where T : struct => Acceleration.FromKilometersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KnotPerHour - - /// - public static Acceleration KnotsPerHour(this T value) => Acceleration.FromKnotsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? KnotsPerHour(this T? value) where T : struct => Acceleration.FromKnotsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KnotPerMinute - - /// - public static Acceleration KnotsPerMinute(this T value) => Acceleration.FromKnotsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? KnotsPerMinute(this T? value) where T : struct => Acceleration.FromKnotsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KnotPerSecond - - /// - public static Acceleration KnotsPerSecond(this T value) => Acceleration.FromKnotsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? KnotsPerSecond(this T? value) where T : struct => Acceleration.FromKnotsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterPerSecondSquared - - /// - public static Acceleration MetersPerSecondSquared(this T value) => Acceleration.FromMetersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? MetersPerSecondSquared(this T? value) where T : struct => Acceleration.FromMetersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrometerPerSecondSquared - - /// - public static Acceleration MicrometersPerSecondSquared(this T value) => Acceleration.FromMicrometersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? MicrometersPerSecondSquared(this T? value) where T : struct => Acceleration.FromMicrometersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterPerSecondSquared - - /// - public static Acceleration MillimetersPerSecondSquared(this T value) => Acceleration.FromMillimetersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? MillimetersPerSecondSquared(this T? value) where T : struct => Acceleration.FromMillimetersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanometerPerSecondSquared - - /// - public static Acceleration NanometersPerSecondSquared(this T value) => Acceleration.FromNanometersPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? NanometersPerSecondSquared(this T? value) where T : struct => Acceleration.FromNanometersPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region StandardGravity - - /// - public static Acceleration StandardGravity(this T value) => Acceleration.FromStandardGravity(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? StandardGravity(this T? value) where T : struct => Acceleration.FromStandardGravity(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmountOfSubstanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmountOfSubstanceExtensions.g.cs deleted file mode 100644 index 63bd57365b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmountOfSubstanceExtensions.g.cs +++ /dev/null @@ -1,214 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAmountOfSubstance -{ - public static class NumberToAmountOfSubstanceExtensions - { - #region Centimole - - /// - public static AmountOfSubstance Centimoles(this T value) => AmountOfSubstance.FromCentimoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Centimoles(this T? value) where T : struct => AmountOfSubstance.FromCentimoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentipoundMole - - /// - public static AmountOfSubstance CentipoundMoles(this T value) => AmountOfSubstance.FromCentipoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? CentipoundMoles(this T? value) where T : struct => AmountOfSubstance.FromCentipoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decimole - - /// - public static AmountOfSubstance Decimoles(this T value) => AmountOfSubstance.FromDecimoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Decimoles(this T? value) where T : struct => AmountOfSubstance.FromDecimoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecipoundMole - - /// - public static AmountOfSubstance DecipoundMoles(this T value) => AmountOfSubstance.FromDecipoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? DecipoundMoles(this T? value) where T : struct => AmountOfSubstance.FromDecipoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilomole - - /// - public static AmountOfSubstance Kilomoles(this T value) => AmountOfSubstance.FromKilomoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Kilomoles(this T? value) where T : struct => AmountOfSubstance.FromKilomoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundMole - - /// - public static AmountOfSubstance KilopoundMoles(this T value) => AmountOfSubstance.FromKilopoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? KilopoundMoles(this T? value) where T : struct => AmountOfSubstance.FromKilopoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megamole - - /// - public static AmountOfSubstance Megamoles(this T value) => AmountOfSubstance.FromMegamoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Megamoles(this T? value) where T : struct => AmountOfSubstance.FromMegamoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Micromole - - /// - public static AmountOfSubstance Micromoles(this T value) => AmountOfSubstance.FromMicromoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Micromoles(this T? value) where T : struct => AmountOfSubstance.FromMicromoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicropoundMole - - /// - public static AmountOfSubstance MicropoundMoles(this T value) => AmountOfSubstance.FromMicropoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? MicropoundMoles(this T? value) where T : struct => AmountOfSubstance.FromMicropoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millimole - - /// - public static AmountOfSubstance Millimoles(this T value) => AmountOfSubstance.FromMillimoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Millimoles(this T? value) where T : struct => AmountOfSubstance.FromMillimoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillipoundMole - - /// - public static AmountOfSubstance MillipoundMoles(this T value) => AmountOfSubstance.FromMillipoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? MillipoundMoles(this T? value) where T : struct => AmountOfSubstance.FromMillipoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Mole - - /// - public static AmountOfSubstance Moles(this T value) => AmountOfSubstance.FromMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Moles(this T? value) where T : struct => AmountOfSubstance.FromMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanomole - - /// - public static AmountOfSubstance Nanomoles(this T value) => AmountOfSubstance.FromNanomoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? Nanomoles(this T? value) where T : struct => AmountOfSubstance.FromNanomoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanopoundMole - - /// - public static AmountOfSubstance NanopoundMoles(this T value) => AmountOfSubstance.FromNanopoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? NanopoundMoles(this T? value) where T : struct => AmountOfSubstance.FromNanopoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundMole - - /// - public static AmountOfSubstance PoundMoles(this T value) => AmountOfSubstance.FromPoundMoles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? PoundMoles(this T? value) where T : struct => AmountOfSubstance.FromPoundMoles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmplitudeRatioExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmplitudeRatioExtensions.g.cs deleted file mode 100644 index c65efd7352..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAmplitudeRatioExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAmplitudeRatio -{ - public static class NumberToAmplitudeRatioExtensions - { - #region DecibelMicrovolt - - /// - public static AmplitudeRatio DecibelMicrovolts(this T value) => AmplitudeRatio.FromDecibelMicrovolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmplitudeRatio? DecibelMicrovolts(this T? value) where T : struct => AmplitudeRatio.FromDecibelMicrovolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecibelMillivolt - - /// - public static AmplitudeRatio DecibelMillivolts(this T value) => AmplitudeRatio.FromDecibelMillivolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmplitudeRatio? DecibelMillivolts(this T? value) where T : struct => AmplitudeRatio.FromDecibelMillivolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecibelUnloaded - - /// - public static AmplitudeRatio DecibelsUnloaded(this T value) => AmplitudeRatio.FromDecibelsUnloaded(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmplitudeRatio? DecibelsUnloaded(this T? value) where T : struct => AmplitudeRatio.FromDecibelsUnloaded(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecibelVolt - - /// - public static AmplitudeRatio DecibelVolts(this T value) => AmplitudeRatio.FromDecibelVolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmplitudeRatio? DecibelVolts(this T? value) where T : struct => AmplitudeRatio.FromDecibelVolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAngleExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAngleExtensions.g.cs deleted file mode 100644 index 7a6a5ef36a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAngleExtensions.g.cs +++ /dev/null @@ -1,203 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAngle -{ - public static class NumberToAngleExtensions - { - #region Arcminute - - /// - public static Angle Arcminutes(this T value) => Angle.FromArcminutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Arcminutes(this T? value) where T : struct => Angle.FromArcminutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Arcsecond - - /// - public static Angle Arcseconds(this T value) => Angle.FromArcseconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Arcseconds(this T? value) where T : struct => Angle.FromArcseconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Centiradian - - /// - public static Angle Centiradians(this T value) => Angle.FromCentiradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Centiradians(this T? value) where T : struct => Angle.FromCentiradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Deciradian - - /// - public static Angle Deciradians(this T value) => Angle.FromDeciradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Deciradians(this T? value) where T : struct => Angle.FromDeciradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Degree - - /// - public static Angle Degrees(this T value) => Angle.FromDegrees(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Degrees(this T? value) where T : struct => Angle.FromDegrees(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gradian - - /// - public static Angle Gradians(this T value) => Angle.FromGradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Gradians(this T? value) where T : struct => Angle.FromGradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microdegree - - /// - public static Angle Microdegrees(this T value) => Angle.FromMicrodegrees(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Microdegrees(this T? value) where T : struct => Angle.FromMicrodegrees(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microradian - - /// - public static Angle Microradians(this T value) => Angle.FromMicroradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Microradians(this T? value) where T : struct => Angle.FromMicroradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millidegree - - /// - public static Angle Millidegrees(this T value) => Angle.FromMillidegrees(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Millidegrees(this T? value) where T : struct => Angle.FromMillidegrees(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milliradian - - /// - public static Angle Milliradians(this T value) => Angle.FromMilliradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Milliradians(this T? value) where T : struct => Angle.FromMilliradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanodegree - - /// - public static Angle Nanodegrees(this T value) => Angle.FromNanodegrees(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Nanodegrees(this T? value) where T : struct => Angle.FromNanodegrees(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanoradian - - /// - public static Angle Nanoradians(this T value) => Angle.FromNanoradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Nanoradians(this T? value) where T : struct => Angle.FromNanoradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Radian - - /// - public static Angle Radians(this T value) => Angle.FromRadians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Radians(this T? value) where T : struct => Angle.FromRadians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Revolution - - /// - public static Angle Revolutions(this T value) => Angle.FromRevolutions(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? Revolutions(this T? value) where T : struct => Angle.FromRevolutions(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentEnergyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentEnergyExtensions.g.cs deleted file mode 100644 index b6ff726836..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentEnergyExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToApparentEnergy -{ - public static class NumberToApparentEnergyExtensions - { - #region KilovoltampereHour - - /// - public static ApparentEnergy KilovoltampereHours(this T value) => ApparentEnergy.FromKilovoltampereHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentEnergy? KilovoltampereHours(this T? value) where T : struct => ApparentEnergy.FromKilovoltampereHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegavoltampereHour - - /// - public static ApparentEnergy MegavoltampereHours(this T value) => ApparentEnergy.FromMegavoltampereHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentEnergy? MegavoltampereHours(this T? value) where T : struct => ApparentEnergy.FromMegavoltampereHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region VoltampereHour - - /// - public static ApparentEnergy VoltampereHours(this T value) => ApparentEnergy.FromVoltampereHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentEnergy? VoltampereHours(this T? value) where T : struct => ApparentEnergy.FromVoltampereHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentPowerExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentPowerExtensions.g.cs deleted file mode 100644 index ad97cdc78e..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToApparentPowerExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToApparentPower -{ - public static class NumberToApparentPowerExtensions - { - #region Gigavoltampere - - /// - public static ApparentPower Gigavoltamperes(this T value) => ApparentPower.FromGigavoltamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentPower? Gigavoltamperes(this T? value) where T : struct => ApparentPower.FromGigavoltamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilovoltampere - - /// - public static ApparentPower Kilovoltamperes(this T value) => ApparentPower.FromKilovoltamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentPower? Kilovoltamperes(this T? value) where T : struct => ApparentPower.FromKilovoltamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megavoltampere - - /// - public static ApparentPower Megavoltamperes(this T value) => ApparentPower.FromMegavoltamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentPower? Megavoltamperes(this T? value) where T : struct => ApparentPower.FromMegavoltamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Voltampere - - /// - public static ApparentPower Voltamperes(this T value) => ApparentPower.FromVoltamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentPower? Voltamperes(this T? value) where T : struct => ApparentPower.FromVoltamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaDensityExtensions.g.cs deleted file mode 100644 index c91ee1b15d..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaDensityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAreaDensity -{ - public static class NumberToAreaDensityExtensions - { - #region KilogramPerSquareMeter - - /// - public static AreaDensity KilogramsPerSquareMeter(this T value) => AreaDensity.FromKilogramsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaDensity? KilogramsPerSquareMeter(this T? value) where T : struct => AreaDensity.FromKilogramsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaExtensions.g.cs deleted file mode 100644 index f9efe3d5f6..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaExtensions.g.cs +++ /dev/null @@ -1,192 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToArea -{ - public static class NumberToAreaExtensions - { - #region Acre - - /// - public static Area Acres(this T value) => Area.FromAcres(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? Acres(this T? value) where T : struct => Area.FromAcres(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hectare - - /// - public static Area Hectares(this T value) => Area.FromHectares(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? Hectares(this T? value) where T : struct => Area.FromHectares(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareCentimeter - - /// - public static Area SquareCentimeters(this T value) => Area.FromSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareCentimeters(this T? value) where T : struct => Area.FromSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareDecimeter - - /// - public static Area SquareDecimeters(this T value) => Area.FromSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareDecimeters(this T? value) where T : struct => Area.FromSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareFoot - - /// - public static Area SquareFeet(this T value) => Area.FromSquareFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareFeet(this T? value) where T : struct => Area.FromSquareFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareInch - - /// - public static Area SquareInches(this T value) => Area.FromSquareInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareInches(this T? value) where T : struct => Area.FromSquareInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareKilometer - - /// - public static Area SquareKilometers(this T value) => Area.FromSquareKilometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareKilometers(this T? value) where T : struct => Area.FromSquareKilometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMeter - - /// - public static Area SquareMeters(this T value) => Area.FromSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareMeters(this T? value) where T : struct => Area.FromSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMicrometer - - /// - public static Area SquareMicrometers(this T value) => Area.FromSquareMicrometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareMicrometers(this T? value) where T : struct => Area.FromSquareMicrometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMile - - /// - public static Area SquareMiles(this T value) => Area.FromSquareMiles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareMiles(this T? value) where T : struct => Area.FromSquareMiles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMillimeter - - /// - public static Area SquareMillimeters(this T value) => Area.FromSquareMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareMillimeters(this T? value) where T : struct => Area.FromSquareMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareYard - - /// - public static Area SquareYards(this T value) => Area.FromSquareYards(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? SquareYards(this T? value) where T : struct => Area.FromSquareYards(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsSurveySquareFoot - - /// - public static Area UsSurveySquareFeet(this T value) => Area.FromUsSurveySquareFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? UsSurveySquareFeet(this T? value) where T : struct => Area.FromUsSurveySquareFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaMomentOfInertiaExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaMomentOfInertiaExtensions.g.cs deleted file mode 100644 index e9a5af6b3f..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToAreaMomentOfInertiaExtensions.g.cs +++ /dev/null @@ -1,115 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToAreaMomentOfInertia -{ - public static class NumberToAreaMomentOfInertiaExtensions - { - #region CentimeterToTheFourth - - /// - public static AreaMomentOfInertia CentimetersToTheFourth(this T value) => AreaMomentOfInertia.FromCentimetersToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? CentimetersToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromCentimetersToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecimeterToTheFourth - - /// - public static AreaMomentOfInertia DecimetersToTheFourth(this T value) => AreaMomentOfInertia.FromDecimetersToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? DecimetersToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromDecimetersToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootToTheFourth - - /// - public static AreaMomentOfInertia FeetToTheFourth(this T value) => AreaMomentOfInertia.FromFeetToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? FeetToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromFeetToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchToTheFourth - - /// - public static AreaMomentOfInertia InchesToTheFourth(this T value) => AreaMomentOfInertia.FromInchesToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? InchesToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromInchesToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterToTheFourth - - /// - public static AreaMomentOfInertia MetersToTheFourth(this T value) => AreaMomentOfInertia.FromMetersToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? MetersToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromMetersToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterToTheFourth - - /// - public static AreaMomentOfInertia MillimetersToTheFourth(this T value) => AreaMomentOfInertia.FromMillimetersToTheFourth(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? MillimetersToTheFourth(this T? value) where T : struct => AreaMomentOfInertia.FromMillimetersToTheFourth(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToBitRateExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToBitRateExtensions.g.cs deleted file mode 100644 index 4efef3834b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToBitRateExtensions.g.cs +++ /dev/null @@ -1,335 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToBitRate -{ - public static class NumberToBitRateExtensions - { - #region BitPerSecond - - /// - public static BitRate BitsPerSecond(this T value) => BitRate.FromBitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? BitsPerSecond(this T? value) where T : struct => BitRate.FromBitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region BytePerSecond - - /// - public static BitRate BytesPerSecond(this T value) => BitRate.FromBytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? BytesPerSecond(this T? value) where T : struct => BitRate.FromBytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ExabitPerSecond - - /// - public static BitRate ExabitsPerSecond(this T value) => BitRate.FromExabitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? ExabitsPerSecond(this T? value) where T : struct => BitRate.FromExabitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ExabytePerSecond - - /// - public static BitRate ExabytesPerSecond(this T value) => BitRate.FromExabytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? ExabytesPerSecond(this T? value) where T : struct => BitRate.FromExabytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ExbibitPerSecond - - /// - public static BitRate ExbibitsPerSecond(this T value) => BitRate.FromExbibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? ExbibitsPerSecond(this T? value) where T : struct => BitRate.FromExbibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ExbibytePerSecond - - /// - public static BitRate ExbibytesPerSecond(this T value) => BitRate.FromExbibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? ExbibytesPerSecond(this T? value) where T : struct => BitRate.FromExbibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GibibitPerSecond - - /// - public static BitRate GibibitsPerSecond(this T value) => BitRate.FromGibibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? GibibitsPerSecond(this T? value) where T : struct => BitRate.FromGibibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GibibytePerSecond - - /// - public static BitRate GibibytesPerSecond(this T value) => BitRate.FromGibibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? GibibytesPerSecond(this T? value) where T : struct => BitRate.FromGibibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigabitPerSecond - - /// - public static BitRate GigabitsPerSecond(this T value) => BitRate.FromGigabitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? GigabitsPerSecond(this T? value) where T : struct => BitRate.FromGigabitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigabytePerSecond - - /// - public static BitRate GigabytesPerSecond(this T value) => BitRate.FromGigabytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? GigabytesPerSecond(this T? value) where T : struct => BitRate.FromGigabytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KibibitPerSecond - - /// - public static BitRate KibibitsPerSecond(this T value) => BitRate.FromKibibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? KibibitsPerSecond(this T? value) where T : struct => BitRate.FromKibibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KibibytePerSecond - - /// - public static BitRate KibibytesPerSecond(this T value) => BitRate.FromKibibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? KibibytesPerSecond(this T? value) where T : struct => BitRate.FromKibibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilobitPerSecond - - /// - public static BitRate KilobitsPerSecond(this T value) => BitRate.FromKilobitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? KilobitsPerSecond(this T? value) where T : struct => BitRate.FromKilobitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilobytePerSecond - - /// - public static BitRate KilobytesPerSecond(this T value) => BitRate.FromKilobytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? KilobytesPerSecond(this T? value) where T : struct => BitRate.FromKilobytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MebibitPerSecond - - /// - public static BitRate MebibitsPerSecond(this T value) => BitRate.FromMebibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? MebibitsPerSecond(this T? value) where T : struct => BitRate.FromMebibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MebibytePerSecond - - /// - public static BitRate MebibytesPerSecond(this T value) => BitRate.FromMebibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? MebibytesPerSecond(this T? value) where T : struct => BitRate.FromMebibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegabitPerSecond - - /// - public static BitRate MegabitsPerSecond(this T value) => BitRate.FromMegabitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? MegabitsPerSecond(this T? value) where T : struct => BitRate.FromMegabitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegabytePerSecond - - /// - public static BitRate MegabytesPerSecond(this T value) => BitRate.FromMegabytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? MegabytesPerSecond(this T? value) where T : struct => BitRate.FromMegabytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PebibitPerSecond - - /// - public static BitRate PebibitsPerSecond(this T value) => BitRate.FromPebibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? PebibitsPerSecond(this T? value) where T : struct => BitRate.FromPebibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PebibytePerSecond - - /// - public static BitRate PebibytesPerSecond(this T value) => BitRate.FromPebibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? PebibytesPerSecond(this T? value) where T : struct => BitRate.FromPebibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PetabitPerSecond - - /// - public static BitRate PetabitsPerSecond(this T value) => BitRate.FromPetabitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? PetabitsPerSecond(this T? value) where T : struct => BitRate.FromPetabitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PetabytePerSecond - - /// - public static BitRate PetabytesPerSecond(this T value) => BitRate.FromPetabytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? PetabytesPerSecond(this T? value) where T : struct => BitRate.FromPetabytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TebibitPerSecond - - /// - public static BitRate TebibitsPerSecond(this T value) => BitRate.FromTebibitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? TebibitsPerSecond(this T? value) where T : struct => BitRate.FromTebibitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TebibytePerSecond - - /// - public static BitRate TebibytesPerSecond(this T value) => BitRate.FromTebibytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? TebibytesPerSecond(this T? value) where T : struct => BitRate.FromTebibytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerabitPerSecond - - /// - public static BitRate TerabitsPerSecond(this T value) => BitRate.FromTerabitsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? TerabitsPerSecond(this T? value) where T : struct => BitRate.FromTerabitsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerabytePerSecond - - /// - public static BitRate TerabytesPerSecond(this T value) => BitRate.FromTerabytesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? TerabytesPerSecond(this T? value) where T : struct => BitRate.FromTerabytesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs deleted file mode 100644 index 1342e04e53..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToBrakeSpecificFuelConsumption -{ - public static class NumberToBrakeSpecificFuelConsumptionExtensions - { - #region GramPerKiloWattHour - - /// - public static BrakeSpecificFuelConsumption GramsPerKiloWattHour(this T value) => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? GramsPerKiloWattHour(this T? value) where T : struct => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerJoule - - /// - public static BrakeSpecificFuelConsumption KilogramsPerJoule(this T value) => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? KilogramsPerJoule(this T? value) where T : struct => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerMechanicalHorsepowerHour - - /// - public static BrakeSpecificFuelConsumption PoundsPerMechanicalHorsepowerHour(this T value) => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? PoundsPerMechanicalHorsepowerHour(this T? value) where T : struct => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToCapacitanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToCapacitanceExtensions.g.cs deleted file mode 100644 index 341484de05..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToCapacitanceExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToCapacitance -{ - public static class NumberToCapacitanceExtensions - { - #region Farad - - /// - public static Capacitance Farads(this T value) => Capacitance.FromFarads(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? Farads(this T? value) where T : struct => Capacitance.FromFarads(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microfarad - - /// - public static Capacitance Microfarads(this T value) => Capacitance.FromMicrofarads(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? Microfarads(this T? value) where T : struct => Capacitance.FromMicrofarads(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millifarad - - /// - public static Capacitance Millifarads(this T value) => Capacitance.FromMillifarads(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? Millifarads(this T? value) where T : struct => Capacitance.FromMillifarads(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanofarad - - /// - public static Capacitance Nanofarads(this T value) => Capacitance.FromNanofarads(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? Nanofarads(this T? value) where T : struct => Capacitance.FromNanofarads(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Picofarad - - /// - public static Capacitance Picofarads(this T value) => Capacitance.FromPicofarads(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? Picofarads(this T? value) where T : struct => Capacitance.FromPicofarads(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToCoefficientOfThermalExpansionExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToCoefficientOfThermalExpansionExtensions.g.cs deleted file mode 100644 index 197d3a0ec9..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToCoefficientOfThermalExpansionExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToCoefficientOfThermalExpansion -{ - public static class NumberToCoefficientOfThermalExpansionExtensions - { - #region InverseDegreeCelsius - - /// - public static CoefficientOfThermalExpansion InverseDegreeCelsius(this T value) => CoefficientOfThermalExpansion.FromInverseDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? InverseDegreeCelsius(this T? value) where T : struct => CoefficientOfThermalExpansion.FromInverseDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InverseDegreeFahrenheit - - /// - public static CoefficientOfThermalExpansion InverseDegreeFahrenheit(this T value) => CoefficientOfThermalExpansion.FromInverseDegreeFahrenheit(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? InverseDegreeFahrenheit(this T? value) where T : struct => CoefficientOfThermalExpansion.FromInverseDegreeFahrenheit(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InverseKelvin - - /// - public static CoefficientOfThermalExpansion InverseKelvin(this T value) => CoefficientOfThermalExpansion.FromInverseKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? InverseKelvin(this T? value) where T : struct => CoefficientOfThermalExpansion.FromInverseKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToDensityExtensions.g.cs deleted file mode 100644 index ea7699b6a7..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDensityExtensions.g.cs +++ /dev/null @@ -1,467 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToDensity -{ - public static class NumberToDensityExtensions - { - #region CentigramPerDeciliter - - /// - public static Density CentigramsPerDeciLiter(this T value) => Density.FromCentigramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? CentigramsPerDeciLiter(this T? value) where T : struct => Density.FromCentigramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentigramPerLiter - - /// - public static Density CentigramsPerLiter(this T value) => Density.FromCentigramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? CentigramsPerLiter(this T? value) where T : struct => Density.FromCentigramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentigramPerMilliliter - - /// - public static Density CentigramsPerMilliliter(this T value) => Density.FromCentigramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? CentigramsPerMilliliter(this T? value) where T : struct => Density.FromCentigramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecigramPerDeciliter - - /// - public static Density DecigramsPerDeciLiter(this T value) => Density.FromDecigramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? DecigramsPerDeciLiter(this T? value) where T : struct => Density.FromDecigramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecigramPerLiter - - /// - public static Density DecigramsPerLiter(this T value) => Density.FromDecigramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? DecigramsPerLiter(this T? value) where T : struct => Density.FromDecigramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecigramPerMilliliter - - /// - public static Density DecigramsPerMilliliter(this T value) => Density.FromDecigramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? DecigramsPerMilliliter(this T? value) where T : struct => Density.FromDecigramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerCubicCentimeter - - /// - public static Density GramsPerCubicCentimeter(this T value) => Density.FromGramsPerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerCubicCentimeter(this T? value) where T : struct => Density.FromGramsPerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerCubicMeter - - /// - public static Density GramsPerCubicMeter(this T value) => Density.FromGramsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerCubicMeter(this T? value) where T : struct => Density.FromGramsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerCubicMillimeter - - /// - public static Density GramsPerCubicMillimeter(this T value) => Density.FromGramsPerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerCubicMillimeter(this T? value) where T : struct => Density.FromGramsPerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerDeciliter - - /// - public static Density GramsPerDeciLiter(this T value) => Density.FromGramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerDeciLiter(this T? value) where T : struct => Density.FromGramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerLiter - - /// - public static Density GramsPerLiter(this T value) => Density.FromGramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerLiter(this T? value) where T : struct => Density.FromGramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerMilliliter - - /// - public static Density GramsPerMilliliter(this T value) => Density.FromGramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? GramsPerMilliliter(this T? value) where T : struct => Density.FromGramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerCubicCentimeter - - /// - public static Density KilogramsPerCubicCentimeter(this T value) => Density.FromKilogramsPerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? KilogramsPerCubicCentimeter(this T? value) where T : struct => Density.FromKilogramsPerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerCubicMeter - - /// - public static Density KilogramsPerCubicMeter(this T value) => Density.FromKilogramsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? KilogramsPerCubicMeter(this T? value) where T : struct => Density.FromKilogramsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerCubicMillimeter - - /// - public static Density KilogramsPerCubicMillimeter(this T value) => Density.FromKilogramsPerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? KilogramsPerCubicMillimeter(this T? value) where T : struct => Density.FromKilogramsPerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundPerCubicFoot - - /// - public static Density KilopoundsPerCubicFoot(this T value) => Density.FromKilopoundsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? KilopoundsPerCubicFoot(this T? value) where T : struct => Density.FromKilopoundsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundPerCubicInch - - /// - public static Density KilopoundsPerCubicInch(this T value) => Density.FromKilopoundsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? KilopoundsPerCubicInch(this T? value) where T : struct => Density.FromKilopoundsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrogramPerDeciliter - - /// - public static Density MicrogramsPerDeciLiter(this T value) => Density.FromMicrogramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MicrogramsPerDeciLiter(this T? value) where T : struct => Density.FromMicrogramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrogramPerLiter - - /// - public static Density MicrogramsPerLiter(this T value) => Density.FromMicrogramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MicrogramsPerLiter(this T? value) where T : struct => Density.FromMicrogramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrogramPerMilliliter - - /// - public static Density MicrogramsPerMilliliter(this T value) => Density.FromMicrogramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MicrogramsPerMilliliter(this T? value) where T : struct => Density.FromMicrogramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerCubicMeter - - /// - public static Density MilligramsPerCubicMeter(this T value) => Density.FromMilligramsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MilligramsPerCubicMeter(this T? value) where T : struct => Density.FromMilligramsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerDeciliter - - /// - public static Density MilligramsPerDeciLiter(this T value) => Density.FromMilligramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MilligramsPerDeciLiter(this T? value) where T : struct => Density.FromMilligramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerLiter - - /// - public static Density MilligramsPerLiter(this T value) => Density.FromMilligramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MilligramsPerLiter(this T? value) where T : struct => Density.FromMilligramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerMilliliter - - /// - public static Density MilligramsPerMilliliter(this T value) => Density.FromMilligramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? MilligramsPerMilliliter(this T? value) where T : struct => Density.FromMilligramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanogramPerDeciliter - - /// - public static Density NanogramsPerDeciLiter(this T value) => Density.FromNanogramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? NanogramsPerDeciLiter(this T? value) where T : struct => Density.FromNanogramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanogramPerLiter - - /// - public static Density NanogramsPerLiter(this T value) => Density.FromNanogramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? NanogramsPerLiter(this T? value) where T : struct => Density.FromNanogramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanogramPerMilliliter - - /// - public static Density NanogramsPerMilliliter(this T value) => Density.FromNanogramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? NanogramsPerMilliliter(this T? value) where T : struct => Density.FromNanogramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicogramPerDeciliter - - /// - public static Density PicogramsPerDeciLiter(this T value) => Density.FromPicogramsPerDeciLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PicogramsPerDeciLiter(this T? value) where T : struct => Density.FromPicogramsPerDeciLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicogramPerLiter - - /// - public static Density PicogramsPerLiter(this T value) => Density.FromPicogramsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PicogramsPerLiter(this T? value) where T : struct => Density.FromPicogramsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicogramPerMilliliter - - /// - public static Density PicogramsPerMilliliter(this T value) => Density.FromPicogramsPerMilliliter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PicogramsPerMilliliter(this T? value) where T : struct => Density.FromPicogramsPerMilliliter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerCubicFoot - - /// - public static Density PoundsPerCubicFoot(this T value) => Density.FromPoundsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PoundsPerCubicFoot(this T? value) where T : struct => Density.FromPoundsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerCubicInch - - /// - public static Density PoundsPerCubicInch(this T value) => Density.FromPoundsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PoundsPerCubicInch(this T? value) where T : struct => Density.FromPoundsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerImperialGallon - - /// - public static Density PoundsPerImperialGallon(this T value) => Density.FromPoundsPerImperialGallon(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PoundsPerImperialGallon(this T? value) where T : struct => Density.FromPoundsPerImperialGallon(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerUSGallon - - /// - public static Density PoundsPerUSGallon(this T value) => Density.FromPoundsPerUSGallon(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? PoundsPerUSGallon(this T? value) where T : struct => Density.FromPoundsPerUSGallon(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SlugPerCubicFoot - - /// - public static Density SlugsPerCubicFoot(this T value) => Density.FromSlugsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? SlugsPerCubicFoot(this T? value) where T : struct => Density.FromSlugsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonnePerCubicCentimeter - - /// - public static Density TonnesPerCubicCentimeter(this T value) => Density.FromTonnesPerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? TonnesPerCubicCentimeter(this T? value) where T : struct => Density.FromTonnesPerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonnePerCubicMeter - - /// - public static Density TonnesPerCubicMeter(this T value) => Density.FromTonnesPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? TonnesPerCubicMeter(this T? value) where T : struct => Density.FromTonnesPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonnePerCubicMillimeter - - /// - public static Density TonnesPerCubicMillimeter(this T value) => Density.FromTonnesPerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? TonnesPerCubicMillimeter(this T? value) where T : struct => Density.FromTonnesPerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDurationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToDurationExtensions.g.cs deleted file mode 100644 index 48e1ccab1a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDurationExtensions.g.cs +++ /dev/null @@ -1,183 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToDuration -{ - public static class NumberToDurationExtensions - { - #region Day - - /// - public static Duration Days(this T value) => Duration.FromDays(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Days(this T? value) where T : struct => Duration.FromDays(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hour - - /// - public static Duration Hours(this T value) => Duration.FromHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Hours(this T? value) where T : struct => Duration.FromHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microsecond - - /// - public static Duration Microseconds(this T value) => Duration.FromMicroseconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Microseconds(this T? value) where T : struct => Duration.FromMicroseconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millisecond - - /// - public static Duration Milliseconds(this T value) => Duration.FromMilliseconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Milliseconds(this T? value) where T : struct => Duration.FromMilliseconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Minute - - /// - public static Duration Minutes(this T value) => Duration.FromMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Minutes(this T? value) where T : struct => Duration.FromMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Month - - /// - [System.Obsolete("Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.")] - public static Duration Months(this T value) => Duration.FromMonths(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Months(this T? value) where T : struct => Duration.FromMonths(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Month30 - - /// - public static Duration Months30(this T value) => Duration.FromMonths30(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Months30(this T? value) where T : struct => Duration.FromMonths30(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanosecond - - /// - public static Duration Nanoseconds(this T value) => Duration.FromNanoseconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Nanoseconds(this T? value) where T : struct => Duration.FromNanoseconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Second - - /// - public static Duration Seconds(this T value) => Duration.FromSeconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Seconds(this T? value) where T : struct => Duration.FromSeconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Week - - /// - public static Duration Weeks(this T value) => Duration.FromWeeks(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Weeks(this T? value) where T : struct => Duration.FromWeeks(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Year - - /// - [System.Obsolete("Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.")] - public static Duration Years(this T value) => Duration.FromYears(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Years(this T? value) where T : struct => Duration.FromYears(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Year365 - - /// - public static Duration Years365(this T value) => Duration.FromYears365(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? Years365(this T? value) where T : struct => Duration.FromYears365(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDynamicViscosityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToDynamicViscosityExtensions.g.cs deleted file mode 100644 index e8af61187f..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToDynamicViscosityExtensions.g.cs +++ /dev/null @@ -1,115 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToDynamicViscosity -{ - public static class NumberToDynamicViscosityExtensions - { - #region Centipoise - - /// - public static DynamicViscosity Centipoise(this T value) => DynamicViscosity.FromCentipoise(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? Centipoise(this T? value) where T : struct => DynamicViscosity.FromCentipoise(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicropascalSecond - - /// - public static DynamicViscosity MicropascalSeconds(this T value) => DynamicViscosity.FromMicropascalSeconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? MicropascalSeconds(this T? value) where T : struct => DynamicViscosity.FromMicropascalSeconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillipascalSecond - - /// - public static DynamicViscosity MillipascalSeconds(this T value) => DynamicViscosity.FromMillipascalSeconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? MillipascalSeconds(this T? value) where T : struct => DynamicViscosity.FromMillipascalSeconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonSecondPerMeterSquared - - /// - public static DynamicViscosity NewtonSecondsPerMeterSquared(this T value) => DynamicViscosity.FromNewtonSecondsPerMeterSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? NewtonSecondsPerMeterSquared(this T? value) where T : struct => DynamicViscosity.FromNewtonSecondsPerMeterSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PascalSecond - - /// - public static DynamicViscosity PascalSeconds(this T value) => DynamicViscosity.FromPascalSeconds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? PascalSeconds(this T? value) where T : struct => DynamicViscosity.FromPascalSeconds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Poise - - /// - public static DynamicViscosity Poise(this T value) => DynamicViscosity.FromPoise(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? Poise(this T? value) where T : struct => DynamicViscosity.FromPoise(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricAdmittanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricAdmittanceExtensions.g.cs deleted file mode 100644 index 479d2dadec..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricAdmittanceExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricAdmittance -{ - public static class NumberToElectricAdmittanceExtensions - { - #region Microsiemens - - /// - public static ElectricAdmittance Microsiemens(this T value) => ElectricAdmittance.FromMicrosiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricAdmittance? Microsiemens(this T? value) where T : struct => ElectricAdmittance.FromMicrosiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millisiemens - - /// - public static ElectricAdmittance Millisiemens(this T value) => ElectricAdmittance.FromMillisiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricAdmittance? Millisiemens(this T? value) where T : struct => ElectricAdmittance.FromMillisiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanosiemens - - /// - public static ElectricAdmittance Nanosiemens(this T value) => ElectricAdmittance.FromNanosiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricAdmittance? Nanosiemens(this T? value) where T : struct => ElectricAdmittance.FromNanosiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Siemens - - /// - public static ElectricAdmittance Siemens(this T value) => ElectricAdmittance.FromSiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricAdmittance? Siemens(this T? value) where T : struct => ElectricAdmittance.FromSiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeDensityExtensions.g.cs deleted file mode 100644 index 8cce5635a8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeDensityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricChargeDensity -{ - public static class NumberToElectricChargeDensityExtensions - { - #region CoulombPerCubicMeter - - /// - public static ElectricChargeDensity CoulombsPerCubicMeter(this T value) => ElectricChargeDensity.FromCoulombsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricChargeDensity? CoulombsPerCubicMeter(this T? value) where T : struct => ElectricChargeDensity.FromCoulombsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeExtensions.g.cs deleted file mode 100644 index 4172b896c6..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricChargeExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricCharge -{ - public static class NumberToElectricChargeExtensions - { - #region Coulomb - - /// - public static ElectricCharge Coulombs(this T value) => ElectricCharge.FromCoulombs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCharge? Coulombs(this T? value) where T : struct => ElectricCharge.FromCoulombs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductanceExtensions.g.cs deleted file mode 100644 index 009d984d58..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductanceExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricConductance -{ - public static class NumberToElectricConductanceExtensions - { - #region Microsiemens - - /// - public static ElectricConductance Microsiemens(this T value) => ElectricConductance.FromMicrosiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductance? Microsiemens(this T? value) where T : struct => ElectricConductance.FromMicrosiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millisiemens - - /// - public static ElectricConductance Millisiemens(this T value) => ElectricConductance.FromMillisiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductance? Millisiemens(this T? value) where T : struct => ElectricConductance.FromMillisiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Siemens - - /// - public static ElectricConductance Siemens(this T value) => ElectricConductance.FromSiemens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductance? Siemens(this T? value) where T : struct => ElectricConductance.FromSiemens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductivityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductivityExtensions.g.cs deleted file mode 100644 index d3f606e246..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricConductivityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricConductivity -{ - public static class NumberToElectricConductivityExtensions - { - #region SiemensPerMeter - - /// - public static ElectricConductivity SiemensPerMeter(this T value) => ElectricConductivity.FromSiemensPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductivity? SiemensPerMeter(this T? value) where T : struct => ElectricConductivity.FromSiemensPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentDensityExtensions.g.cs deleted file mode 100644 index efd6ced57a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentDensityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricCurrentDensity -{ - public static class NumberToElectricCurrentDensityExtensions - { - #region AmperePerSquareMeter - - /// - public static ElectricCurrentDensity AmperesPerSquareMeter(this T value) => ElectricCurrentDensity.FromAmperesPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrentDensity? AmperesPerSquareMeter(this T? value) where T : struct => ElectricCurrentDensity.FromAmperesPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentExtensions.g.cs deleted file mode 100644 index cc6432cea8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricCurrent -{ - public static class NumberToElectricCurrentExtensions - { - #region Ampere - - /// - public static ElectricCurrent Amperes(this T value) => ElectricCurrent.FromAmperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Amperes(this T? value) where T : struct => ElectricCurrent.FromAmperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Centiampere - - /// - public static ElectricCurrent Centiamperes(this T value) => ElectricCurrent.FromCentiamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Centiamperes(this T? value) where T : struct => ElectricCurrent.FromCentiamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kiloampere - - /// - public static ElectricCurrent Kiloamperes(this T value) => ElectricCurrent.FromKiloamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Kiloamperes(this T? value) where T : struct => ElectricCurrent.FromKiloamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megaampere - - /// - public static ElectricCurrent Megaamperes(this T value) => ElectricCurrent.FromMegaamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Megaamperes(this T? value) where T : struct => ElectricCurrent.FromMegaamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microampere - - /// - public static ElectricCurrent Microamperes(this T value) => ElectricCurrent.FromMicroamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Microamperes(this T? value) where T : struct => ElectricCurrent.FromMicroamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milliampere - - /// - public static ElectricCurrent Milliamperes(this T value) => ElectricCurrent.FromMilliamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Milliamperes(this T? value) where T : struct => ElectricCurrent.FromMilliamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanoampere - - /// - public static ElectricCurrent Nanoamperes(this T value) => ElectricCurrent.FromNanoamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Nanoamperes(this T? value) where T : struct => ElectricCurrent.FromNanoamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Picoampere - - /// - public static ElectricCurrent Picoamperes(this T value) => ElectricCurrent.FromPicoamperes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? Picoamperes(this T? value) where T : struct => ElectricCurrent.FromPicoamperes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentGradientExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentGradientExtensions.g.cs deleted file mode 100644 index f8ff56e216..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricCurrentGradientExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricCurrentGradient -{ - public static class NumberToElectricCurrentGradientExtensions - { - #region AmperePerSecond - - /// - public static ElectricCurrentGradient AmperesPerSecond(this T value) => ElectricCurrentGradient.FromAmperesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrentGradient? AmperesPerSecond(this T? value) where T : struct => ElectricCurrentGradient.FromAmperesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricFieldExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricFieldExtensions.g.cs deleted file mode 100644 index dd03e3351a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricFieldExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricField -{ - public static class NumberToElectricFieldExtensions - { - #region VoltPerMeter - - /// - public static ElectricField VoltsPerMeter(this T value) => ElectricField.FromVoltsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricField? VoltsPerMeter(this T? value) where T : struct => ElectricField.FromVoltsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricInductanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricInductanceExtensions.g.cs deleted file mode 100644 index 5ebb3fae37..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricInductanceExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricInductance -{ - public static class NumberToElectricInductanceExtensions - { - #region Henry - - /// - public static ElectricInductance Henries(this T value) => ElectricInductance.FromHenries(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricInductance? Henries(this T? value) where T : struct => ElectricInductance.FromHenries(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microhenry - - /// - public static ElectricInductance Microhenries(this T value) => ElectricInductance.FromMicrohenries(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricInductance? Microhenries(this T? value) where T : struct => ElectricInductance.FromMicrohenries(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millihenry - - /// - public static ElectricInductance Millihenries(this T value) => ElectricInductance.FromMillihenries(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricInductance? Millihenries(this T? value) where T : struct => ElectricInductance.FromMillihenries(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanohenry - - /// - public static ElectricInductance Nanohenries(this T value) => ElectricInductance.FromNanohenries(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricInductance? Nanohenries(this T? value) where T : struct => ElectricInductance.FromNanohenries(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialAcExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialAcExtensions.g.cs deleted file mode 100644 index 2e0562ea00..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialAcExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricPotentialAc -{ - public static class NumberToElectricPotentialAcExtensions - { - #region KilovoltAc - - /// - public static ElectricPotentialAc KilovoltsAc(this T value) => ElectricPotentialAc.FromKilovoltsAc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? KilovoltsAc(this T? value) where T : struct => ElectricPotentialAc.FromKilovoltsAc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegavoltAc - - /// - public static ElectricPotentialAc MegavoltsAc(this T value) => ElectricPotentialAc.FromMegavoltsAc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? MegavoltsAc(this T? value) where T : struct => ElectricPotentialAc.FromMegavoltsAc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrovoltAc - - /// - public static ElectricPotentialAc MicrovoltsAc(this T value) => ElectricPotentialAc.FromMicrovoltsAc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? MicrovoltsAc(this T? value) where T : struct => ElectricPotentialAc.FromMicrovoltsAc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillivoltAc - - /// - public static ElectricPotentialAc MillivoltsAc(this T value) => ElectricPotentialAc.FromMillivoltsAc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? MillivoltsAc(this T? value) where T : struct => ElectricPotentialAc.FromMillivoltsAc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region VoltAc - - /// - public static ElectricPotentialAc VoltsAc(this T value) => ElectricPotentialAc.FromVoltsAc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? VoltsAc(this T? value) where T : struct => ElectricPotentialAc.FromVoltsAc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialDcExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialDcExtensions.g.cs deleted file mode 100644 index fde616f3e2..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialDcExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricPotentialDc -{ - public static class NumberToElectricPotentialDcExtensions - { - #region KilovoltDc - - /// - public static ElectricPotentialDc KilovoltsDc(this T value) => ElectricPotentialDc.FromKilovoltsDc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? KilovoltsDc(this T? value) where T : struct => ElectricPotentialDc.FromKilovoltsDc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegavoltDc - - /// - public static ElectricPotentialDc MegavoltsDc(this T value) => ElectricPotentialDc.FromMegavoltsDc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? MegavoltsDc(this T? value) where T : struct => ElectricPotentialDc.FromMegavoltsDc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrovoltDc - - /// - public static ElectricPotentialDc MicrovoltsDc(this T value) => ElectricPotentialDc.FromMicrovoltsDc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? MicrovoltsDc(this T? value) where T : struct => ElectricPotentialDc.FromMicrovoltsDc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillivoltDc - - /// - public static ElectricPotentialDc MillivoltsDc(this T value) => ElectricPotentialDc.FromMillivoltsDc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? MillivoltsDc(this T? value) where T : struct => ElectricPotentialDc.FromMillivoltsDc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region VoltDc - - /// - public static ElectricPotentialDc VoltsDc(this T value) => ElectricPotentialDc.FromVoltsDc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? VoltsDc(this T? value) where T : struct => ElectricPotentialDc.FromVoltsDc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialExtensions.g.cs deleted file mode 100644 index 4d65056731..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricPotentialExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricPotential -{ - public static class NumberToElectricPotentialExtensions - { - #region Kilovolt - - /// - public static ElectricPotential Kilovolts(this T value) => ElectricPotential.FromKilovolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? Kilovolts(this T? value) where T : struct => ElectricPotential.FromKilovolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megavolt - - /// - public static ElectricPotential Megavolts(this T value) => ElectricPotential.FromMegavolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? Megavolts(this T? value) where T : struct => ElectricPotential.FromMegavolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microvolt - - /// - public static ElectricPotential Microvolts(this T value) => ElectricPotential.FromMicrovolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? Microvolts(this T? value) where T : struct => ElectricPotential.FromMicrovolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millivolt - - /// - public static ElectricPotential Millivolts(this T value) => ElectricPotential.FromMillivolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? Millivolts(this T? value) where T : struct => ElectricPotential.FromMillivolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Volt - - /// - public static ElectricPotential Volts(this T value) => ElectricPotential.FromVolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? Volts(this T? value) where T : struct => ElectricPotential.FromVolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistanceExtensions.g.cs deleted file mode 100644 index a105b72267..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistanceExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricResistance -{ - public static class NumberToElectricResistanceExtensions - { - #region Gigaohm - - /// - public static ElectricResistance Gigaohms(this T value) => ElectricResistance.FromGigaohms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? Gigaohms(this T? value) where T : struct => ElectricResistance.FromGigaohms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kiloohm - - /// - public static ElectricResistance Kiloohms(this T value) => ElectricResistance.FromKiloohms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? Kiloohms(this T? value) where T : struct => ElectricResistance.FromKiloohms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megaohm - - /// - public static ElectricResistance Megaohms(this T value) => ElectricResistance.FromMegaohms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? Megaohms(this T? value) where T : struct => ElectricResistance.FromMegaohms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milliohm - - /// - public static ElectricResistance Milliohms(this T value) => ElectricResistance.FromMilliohms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? Milliohms(this T? value) where T : struct => ElectricResistance.FromMilliohms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Ohm - - /// - public static ElectricResistance Ohms(this T value) => ElectricResistance.FromOhms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? Ohms(this T? value) where T : struct => ElectricResistance.FromOhms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistivityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistivityExtensions.g.cs deleted file mode 100644 index 1ef50dabd8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricResistivityExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToElectricResistivity -{ - public static class NumberToElectricResistivityExtensions - { - #region MicroohmMeter - - /// - public static ElectricResistivity MicroohmMeters(this T value) => ElectricResistivity.FromMicroohmMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistivity? MicroohmMeters(this T? value) where T : struct => ElectricResistivity.FromMicroohmMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliohmMeter - - /// - public static ElectricResistivity MilliohmMeters(this T value) => ElectricResistivity.FromMilliohmMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistivity? MilliohmMeters(this T? value) where T : struct => ElectricResistivity.FromMilliohmMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanoohmMeter - - /// - public static ElectricResistivity NanoohmMeters(this T value) => ElectricResistivity.FromNanoohmMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistivity? NanoohmMeters(this T? value) where T : struct => ElectricResistivity.FromNanoohmMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OhmMeter - - /// - public static ElectricResistivity OhmMeters(this T value) => ElectricResistivity.FromOhmMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistivity? OhmMeters(this T? value) where T : struct => ElectricResistivity.FromOhmMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToEnergyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToEnergyExtensions.g.cs deleted file mode 100644 index f1b22c4470..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToEnergyExtensions.g.cs +++ /dev/null @@ -1,291 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToEnergy -{ - public static class NumberToEnergyExtensions - { - #region BritishThermalUnit - - /// - public static Energy BritishThermalUnits(this T value) => Energy.FromBritishThermalUnits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? BritishThermalUnits(this T? value) where T : struct => Energy.FromBritishThermalUnits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Calorie - - /// - public static Energy Calories(this T value) => Energy.FromCalories(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Calories(this T? value) where T : struct => Energy.FromCalories(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecathermEc - - /// - public static Energy DecathermsEc(this T value) => Energy.FromDecathermsEc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? DecathermsEc(this T? value) where T : struct => Energy.FromDecathermsEc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecathermImperial - - /// - public static Energy DecathermsImperial(this T value) => Energy.FromDecathermsImperial(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? DecathermsImperial(this T? value) where T : struct => Energy.FromDecathermsImperial(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecathermUs - - /// - public static Energy DecathermsUs(this T value) => Energy.FromDecathermsUs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? DecathermsUs(this T? value) where T : struct => Energy.FromDecathermsUs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ElectronVolt - - /// - public static Energy ElectronVolts(this T value) => Energy.FromElectronVolts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? ElectronVolts(this T? value) where T : struct => Energy.FromElectronVolts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Erg - - /// - public static Energy Ergs(this T value) => Energy.FromErgs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Ergs(this T? value) where T : struct => Energy.FromErgs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootPound - - /// - public static Energy FootPounds(this T value) => Energy.FromFootPounds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? FootPounds(this T? value) where T : struct => Energy.FromFootPounds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigabritishThermalUnit - - /// - public static Energy GigabritishThermalUnits(this T value) => Energy.FromGigabritishThermalUnits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? GigabritishThermalUnits(this T? value) where T : struct => Energy.FromGigabritishThermalUnits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigawattHour - - /// - public static Energy GigawattHours(this T value) => Energy.FromGigawattHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? GigawattHours(this T? value) where T : struct => Energy.FromGigawattHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Joule - - /// - public static Energy Joules(this T value) => Energy.FromJoules(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Joules(this T? value) where T : struct => Energy.FromJoules(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilobritishThermalUnit - - /// - public static Energy KilobritishThermalUnits(this T value) => Energy.FromKilobritishThermalUnits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? KilobritishThermalUnits(this T? value) where T : struct => Energy.FromKilobritishThermalUnits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilocalorie - - /// - public static Energy Kilocalories(this T value) => Energy.FromKilocalories(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Kilocalories(this T? value) where T : struct => Energy.FromKilocalories(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilojoule - - /// - public static Energy Kilojoules(this T value) => Energy.FromKilojoules(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Kilojoules(this T? value) where T : struct => Energy.FromKilojoules(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattHour - - /// - public static Energy KilowattHours(this T value) => Energy.FromKilowattHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? KilowattHours(this T? value) where T : struct => Energy.FromKilowattHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegabritishThermalUnit - - /// - public static Energy MegabritishThermalUnits(this T value) => Energy.FromMegabritishThermalUnits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? MegabritishThermalUnits(this T? value) where T : struct => Energy.FromMegabritishThermalUnits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megajoule - - /// - public static Energy Megajoules(this T value) => Energy.FromMegajoules(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? Megajoules(this T? value) where T : struct => Energy.FromMegajoules(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattHour - - /// - public static Energy MegawattHours(this T value) => Energy.FromMegawattHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? MegawattHours(this T? value) where T : struct => Energy.FromMegawattHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ThermEc - - /// - public static Energy ThermsEc(this T value) => Energy.FromThermsEc(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? ThermsEc(this T? value) where T : struct => Energy.FromThermsEc(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ThermImperial - - /// - public static Energy ThermsImperial(this T value) => Energy.FromThermsImperial(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? ThermsImperial(this T? value) where T : struct => Energy.FromThermsImperial(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ThermUs - - /// - public static Energy ThermsUs(this T value) => Energy.FromThermsUs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? ThermsUs(this T? value) where T : struct => Energy.FromThermsUs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattHour - - /// - public static Energy WattHours(this T value) => Energy.FromWattHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? WattHours(this T? value) where T : struct => Energy.FromWattHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToEntropyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToEntropyExtensions.g.cs deleted file mode 100644 index 0c83b6987b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToEntropyExtensions.g.cs +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToEntropy -{ - public static class NumberToEntropyExtensions - { - #region CaloriePerKelvin - - /// - public static Entropy CaloriesPerKelvin(this T value) => Entropy.FromCaloriesPerKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? CaloriesPerKelvin(this T? value) where T : struct => Entropy.FromCaloriesPerKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region JoulePerDegreeCelsius - - /// - public static Entropy JoulesPerDegreeCelsius(this T value) => Entropy.FromJoulesPerDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? JoulesPerDegreeCelsius(this T? value) where T : struct => Entropy.FromJoulesPerDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region JoulePerKelvin - - /// - public static Entropy JoulesPerKelvin(this T value) => Entropy.FromJoulesPerKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? JoulesPerKelvin(this T? value) where T : struct => Entropy.FromJoulesPerKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocaloriePerKelvin - - /// - public static Entropy KilocaloriesPerKelvin(this T value) => Entropy.FromKilocaloriesPerKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? KilocaloriesPerKelvin(this T? value) where T : struct => Entropy.FromKilocaloriesPerKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerDegreeCelsius - - /// - public static Entropy KilojoulesPerDegreeCelsius(this T value) => Entropy.FromKilojoulesPerDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? KilojoulesPerDegreeCelsius(this T? value) where T : struct => Entropy.FromKilojoulesPerDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerKelvin - - /// - public static Entropy KilojoulesPerKelvin(this T value) => Entropy.FromKilojoulesPerKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? KilojoulesPerKelvin(this T? value) where T : struct => Entropy.FromKilojoulesPerKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerKelvin - - /// - public static Entropy MegajoulesPerKelvin(this T value) => Entropy.FromMegajoulesPerKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? MegajoulesPerKelvin(this T? value) where T : struct => Entropy.FromMegajoulesPerKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToFlowExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToFlowExtensions.g.cs deleted file mode 100644 index 6fdb1b2fa7..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToFlowExtensions.g.cs +++ /dev/null @@ -1,331 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToFlow -{ - public static class NumberToFlowExtensions - { - #region CentilitersPerMinute - - /// - public static Flow CentilitersPerMinute(this T value) => Flow.FromCentilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CentilitersPerMinute(this T? value) where T : struct => Flow.FromCentilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicDecimeterPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicDecimetersPerMinute(this T value) => Flow.FromCubicDecimetersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicDecimetersPerMinute(this T? value) where T : struct => Flow.FromCubicDecimetersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerHour - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicFeetPerHour(this T value) => Flow.FromCubicFeetPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicFeetPerHour(this T? value) where T : struct => Flow.FromCubicFeetPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicFeetPerMinute(this T value) => Flow.FromCubicFeetPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicFeetPerMinute(this T? value) where T : struct => Flow.FromCubicFeetPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerSecond - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicFeetPerSecond(this T value) => Flow.FromCubicFeetPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicFeetPerSecond(this T? value) where T : struct => Flow.FromCubicFeetPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerHour - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicMetersPerHour(this T value) => Flow.FromCubicMetersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicMetersPerHour(this T? value) where T : struct => Flow.FromCubicMetersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicMetersPerMinute(this T value) => Flow.FromCubicMetersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicMetersPerMinute(this T? value) where T : struct => Flow.FromCubicMetersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerSecond - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicMetersPerSecond(this T value) => Flow.FromCubicMetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicMetersPerSecond(this T? value) where T : struct => Flow.FromCubicMetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerHour - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicYardsPerHour(this T value) => Flow.FromCubicYardsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicYardsPerHour(this T? value) where T : struct => Flow.FromCubicYardsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicYardsPerMinute(this T value) => Flow.FromCubicYardsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicYardsPerMinute(this T? value) where T : struct => Flow.FromCubicYardsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerSecond - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow CubicYardsPerSecond(this T value) => Flow.FromCubicYardsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? CubicYardsPerSecond(this T? value) where T : struct => Flow.FromCubicYardsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecilitersPerMinute - - /// - public static Flow DecilitersPerMinute(this T value) => Flow.FromDecilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? DecilitersPerMinute(this T? value) where T : struct => Flow.FromDecilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilolitersPerMinute - - /// - public static Flow KilolitersPerMinute(this T value) => Flow.FromKilolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? KilolitersPerMinute(this T? value) where T : struct => Flow.FromKilolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerHour - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow LitersPerHour(this T value) => Flow.FromLitersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? LitersPerHour(this T? value) where T : struct => Flow.FromLitersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow LitersPerMinute(this T value) => Flow.FromLitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? LitersPerMinute(this T? value) where T : struct => Flow.FromLitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerSecond - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow LitersPerSecond(this T value) => Flow.FromLitersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? LitersPerSecond(this T? value) where T : struct => Flow.FromLitersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrolitersPerMinute - - /// - public static Flow MicrolitersPerMinute(this T value) => Flow.FromMicrolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? MicrolitersPerMinute(this T? value) where T : struct => Flow.FromMicrolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillilitersPerMinute - - /// - public static Flow MillilitersPerMinute(this T value) => Flow.FromMillilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? MillilitersPerMinute(this T? value) where T : struct => Flow.FromMillilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillionUsGallonsPerDay - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow MillionUsGallonsPerDay(this T value) => Flow.FromMillionUsGallonsPerDay(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? MillionUsGallonsPerDay(this T? value) where T : struct => Flow.FromMillionUsGallonsPerDay(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanolitersPerMinute - - /// - public static Flow NanolitersPerMinute(this T value) => Flow.FromNanolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? NanolitersPerMinute(this T? value) where T : struct => Flow.FromNanolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OilBarrelsPerDay - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow OilBarrelsPerDay(this T value) => Flow.FromOilBarrelsPerDay(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? OilBarrelsPerDay(this T? value) where T : struct => Flow.FromOilBarrelsPerDay(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerHour - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow UsGallonsPerHour(this T value) => Flow.FromUsGallonsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? UsGallonsPerHour(this T? value) where T : struct => Flow.FromUsGallonsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerMinute - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow UsGallonsPerMinute(this T value) => Flow.FromUsGallonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? UsGallonsPerMinute(this T? value) where T : struct => Flow.FromUsGallonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerSecond - - /// - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public static Flow UsGallonsPerSecond(this T value) => Flow.FromUsGallonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? UsGallonsPerSecond(this T? value) where T : struct => Flow.FromUsGallonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceChangeRateExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceChangeRateExtensions.g.cs deleted file mode 100644 index 4e9fd9075b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceChangeRateExtensions.g.cs +++ /dev/null @@ -1,170 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToForceChangeRate -{ - public static class NumberToForceChangeRateExtensions - { - #region CentinewtonPerSecond - - /// - public static ForceChangeRate CentinewtonsPerSecond(this T value) => ForceChangeRate.FromCentinewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? CentinewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromCentinewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecanewtonPerMinute - - /// - public static ForceChangeRate DecanewtonsPerMinute(this T value) => ForceChangeRate.FromDecanewtonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? DecanewtonsPerMinute(this T? value) where T : struct => ForceChangeRate.FromDecanewtonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecanewtonPerSecond - - /// - public static ForceChangeRate DecanewtonsPerSecond(this T value) => ForceChangeRate.FromDecanewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? DecanewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromDecanewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecinewtonPerSecond - - /// - public static ForceChangeRate DecinewtonsPerSecond(this T value) => ForceChangeRate.FromDecinewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? DecinewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromDecinewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerMinute - - /// - public static ForceChangeRate KilonewtonsPerMinute(this T value) => ForceChangeRate.FromKilonewtonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? KilonewtonsPerMinute(this T? value) where T : struct => ForceChangeRate.FromKilonewtonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerSecond - - /// - public static ForceChangeRate KilonewtonsPerSecond(this T value) => ForceChangeRate.FromKilonewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? KilonewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromKilonewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicronewtonPerSecond - - /// - public static ForceChangeRate MicronewtonsPerSecond(this T value) => ForceChangeRate.FromMicronewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? MicronewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromMicronewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillinewtonPerSecond - - /// - public static ForceChangeRate MillinewtonsPerSecond(this T value) => ForceChangeRate.FromMillinewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? MillinewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromMillinewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanonewtonPerSecond - - /// - public static ForceChangeRate NanonewtonsPerSecond(this T value) => ForceChangeRate.FromNanonewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? NanonewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromNanonewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerMinute - - /// - public static ForceChangeRate NewtonsPerMinute(this T value) => ForceChangeRate.FromNewtonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? NewtonsPerMinute(this T? value) where T : struct => ForceChangeRate.FromNewtonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerSecond - - /// - public static ForceChangeRate NewtonsPerSecond(this T value) => ForceChangeRate.FromNewtonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? NewtonsPerSecond(this T? value) where T : struct => ForceChangeRate.FromNewtonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceExtensions.g.cs deleted file mode 100644 index bbb2e5b140..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForceExtensions.g.cs +++ /dev/null @@ -1,192 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToForce -{ - public static class NumberToForceExtensions - { - #region Decanewton - - /// - public static Force Decanewtons(this T value) => Force.FromDecanewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Decanewtons(this T? value) where T : struct => Force.FromDecanewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Dyn - - /// - public static Force Dyne(this T value) => Force.FromDyne(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Dyne(this T? value) where T : struct => Force.FromDyne(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForce - - /// - public static Force KilogramsForce(this T value) => Force.FromKilogramsForce(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? KilogramsForce(this T? value) where T : struct => Force.FromKilogramsForce(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilonewton - - /// - public static Force Kilonewtons(this T value) => Force.FromKilonewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Kilonewtons(this T? value) where T : struct => Force.FromKilonewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KiloPond - - /// - public static Force KiloPonds(this T value) => Force.FromKiloPonds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? KiloPonds(this T? value) where T : struct => Force.FromKiloPonds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Meganewton - - /// - public static Force Meganewtons(this T value) => Force.FromMeganewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Meganewtons(this T? value) where T : struct => Force.FromMeganewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Micronewton - - /// - public static Force Micronewtons(this T value) => Force.FromMicronewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Micronewtons(this T? value) where T : struct => Force.FromMicronewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millinewton - - /// - public static Force Millinewtons(this T value) => Force.FromMillinewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Millinewtons(this T? value) where T : struct => Force.FromMillinewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Newton - - /// - public static Force Newtons(this T value) => Force.FromNewtons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Newtons(this T? value) where T : struct => Force.FromNewtons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OunceForce - - /// - public static Force OunceForce(this T value) => Force.FromOunceForce(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? OunceForce(this T? value) where T : struct => Force.FromOunceForce(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Poundal - - /// - public static Force Poundals(this T value) => Force.FromPoundals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? Poundals(this T? value) where T : struct => Force.FromPoundals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForce - - /// - public static Force PoundsForce(this T value) => Force.FromPoundsForce(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? PoundsForce(this T? value) where T : struct => Force.FromPoundsForce(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForce - - /// - public static Force TonnesForce(this T value) => Force.FromTonnesForce(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? TonnesForce(this T? value) where T : struct => Force.FromTonnesForce(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForcePerLengthExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToForcePerLengthExtensions.g.cs deleted file mode 100644 index 6db097dcd1..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToForcePerLengthExtensions.g.cs +++ /dev/null @@ -1,148 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToForcePerLength -{ - public static class NumberToForcePerLengthExtensions - { - #region CentinewtonPerMeter - - /// - public static ForcePerLength CentinewtonsPerMeter(this T value) => ForcePerLength.FromCentinewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? CentinewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromCentinewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecinewtonPerMeter - - /// - public static ForcePerLength DecinewtonsPerMeter(this T value) => ForcePerLength.FromDecinewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? DecinewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromDecinewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerMeter - - /// - public static ForcePerLength KilogramsForcePerMeter(this T value) => ForcePerLength.FromKilogramsForcePerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? KilogramsForcePerMeter(this T? value) where T : struct => ForcePerLength.FromKilogramsForcePerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerMeter - - /// - public static ForcePerLength KilonewtonsPerMeter(this T value) => ForcePerLength.FromKilonewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? KilonewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromKilonewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonPerMeter - - /// - public static ForcePerLength MeganewtonsPerMeter(this T value) => ForcePerLength.FromMeganewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? MeganewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromMeganewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicronewtonPerMeter - - /// - public static ForcePerLength MicronewtonsPerMeter(this T value) => ForcePerLength.FromMicronewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? MicronewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromMicronewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillinewtonPerMeter - - /// - public static ForcePerLength MillinewtonsPerMeter(this T value) => ForcePerLength.FromMillinewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? MillinewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromMillinewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanonewtonPerMeter - - /// - public static ForcePerLength NanonewtonsPerMeter(this T value) => ForcePerLength.FromNanonewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? NanonewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromNanonewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerMeter - - /// - public static ForcePerLength NewtonsPerMeter(this T value) => ForcePerLength.FromNewtonsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? NewtonsPerMeter(this T? value) where T : struct => ForcePerLength.FromNewtonsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToFrequencyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToFrequencyExtensions.g.cs deleted file mode 100644 index d9628a6665..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToFrequencyExtensions.g.cs +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToFrequency -{ - public static class NumberToFrequencyExtensions - { - #region CyclePerHour - - /// - public static Frequency CyclesPerHour(this T value) => Frequency.FromCyclesPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? CyclesPerHour(this T? value) where T : struct => Frequency.FromCyclesPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CyclePerMinute - - /// - public static Frequency CyclesPerMinute(this T value) => Frequency.FromCyclesPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? CyclesPerMinute(this T? value) where T : struct => Frequency.FromCyclesPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gigahertz - - /// - public static Frequency Gigahertz(this T value) => Frequency.FromGigahertz(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? Gigahertz(this T? value) where T : struct => Frequency.FromGigahertz(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hertz - - /// - public static Frequency Hertz(this T value) => Frequency.FromHertz(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? Hertz(this T? value) where T : struct => Frequency.FromHertz(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilohertz - - /// - public static Frequency Kilohertz(this T value) => Frequency.FromKilohertz(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? Kilohertz(this T? value) where T : struct => Frequency.FromKilohertz(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megahertz - - /// - public static Frequency Megahertz(this T value) => Frequency.FromMegahertz(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? Megahertz(this T? value) where T : struct => Frequency.FromMegahertz(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Terahertz - - /// - public static Frequency Terahertz(this T value) => Frequency.FromTerahertz(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? Terahertz(this T? value) where T : struct => Frequency.FromTerahertz(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatFluxExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatFluxExtensions.g.cs deleted file mode 100644 index e3083c0f07..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatFluxExtensions.g.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToHeatFlux -{ - public static class NumberToHeatFluxExtensions - { - #region BtuPerHourSquareFoot - - /// - public static HeatFlux BtusPerHourSquareFoot(this T value) => HeatFlux.FromBtusPerHourSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? BtusPerHourSquareFoot(this T? value) where T : struct => HeatFlux.FromBtusPerHourSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region BtuPerMinuteSquareFoot - - /// - public static HeatFlux BtusPerMinuteSquareFoot(this T value) => HeatFlux.FromBtusPerMinuteSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? BtusPerMinuteSquareFoot(this T? value) where T : struct => HeatFlux.FromBtusPerMinuteSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region BtuPerSecondSquareFoot - - /// - public static HeatFlux BtusPerSecondSquareFoot(this T value) => HeatFlux.FromBtusPerSecondSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? BtusPerSecondSquareFoot(this T? value) where T : struct => HeatFlux.FromBtusPerSecondSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region BtuPerSecondSquareInch - - /// - public static HeatFlux BtusPerSecondSquareInch(this T value) => HeatFlux.FromBtusPerSecondSquareInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? BtusPerSecondSquareInch(this T? value) where T : struct => HeatFlux.FromBtusPerSecondSquareInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CaloriePerSecondSquareCentimeter - - /// - public static HeatFlux CaloriesPerSecondSquareCentimeter(this T value) => HeatFlux.FromCaloriesPerSecondSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? CaloriesPerSecondSquareCentimeter(this T? value) where T : struct => HeatFlux.FromCaloriesPerSecondSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentiwattPerSquareMeter - - /// - public static HeatFlux CentiwattsPerSquareMeter(this T value) => HeatFlux.FromCentiwattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? CentiwattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromCentiwattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciwattPerSquareMeter - - /// - public static HeatFlux DeciwattsPerSquareMeter(this T value) => HeatFlux.FromDeciwattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? DeciwattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromDeciwattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocaloriePerHourSquareMeter - - /// - public static HeatFlux KilocaloriesPerHourSquareMeter(this T value) => HeatFlux.FromKilocaloriesPerHourSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? KilocaloriesPerHourSquareMeter(this T? value) where T : struct => HeatFlux.FromKilocaloriesPerHourSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocaloriePerSecondSquareCentimeter - - /// - public static HeatFlux KilocaloriesPerSecondSquareCentimeter(this T value) => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? KilocaloriesPerSecondSquareCentimeter(this T? value) where T : struct => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattPerSquareMeter - - /// - public static HeatFlux KilowattsPerSquareMeter(this T value) => HeatFlux.FromKilowattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? KilowattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromKilowattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrowattPerSquareMeter - - /// - public static HeatFlux MicrowattsPerSquareMeter(this T value) => HeatFlux.FromMicrowattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? MicrowattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromMicrowattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliwattPerSquareMeter - - /// - public static HeatFlux MilliwattsPerSquareMeter(this T value) => HeatFlux.FromMilliwattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? MilliwattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromMilliwattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanowattPerSquareMeter - - /// - public static HeatFlux NanowattsPerSquareMeter(this T value) => HeatFlux.FromNanowattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? NanowattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromNanowattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForcePerFootSecond - - /// - public static HeatFlux PoundsForcePerFootSecond(this T value) => HeatFlux.FromPoundsForcePerFootSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? PoundsForcePerFootSecond(this T? value) where T : struct => HeatFlux.FromPoundsForcePerFootSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerSecondCubed - - /// - public static HeatFlux PoundsPerSecondCubed(this T value) => HeatFlux.FromPoundsPerSecondCubed(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? PoundsPerSecondCubed(this T? value) where T : struct => HeatFlux.FromPoundsPerSecondCubed(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerSquareFoot - - /// - public static HeatFlux WattsPerSquareFoot(this T value) => HeatFlux.FromWattsPerSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? WattsPerSquareFoot(this T? value) where T : struct => HeatFlux.FromWattsPerSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerSquareInch - - /// - public static HeatFlux WattsPerSquareInch(this T value) => HeatFlux.FromWattsPerSquareInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? WattsPerSquareInch(this T? value) where T : struct => HeatFlux.FromWattsPerSquareInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerSquareMeter - - /// - public static HeatFlux WattsPerSquareMeter(this T value) => HeatFlux.FromWattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? WattsPerSquareMeter(this T? value) where T : struct => HeatFlux.FromWattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatTransferCoefficientExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatTransferCoefficientExtensions.g.cs deleted file mode 100644 index 95b2497adf..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToHeatTransferCoefficientExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToHeatTransferCoefficient -{ - public static class NumberToHeatTransferCoefficientExtensions - { - #region WattPerSquareMeterCelsius - - /// - public static HeatTransferCoefficient WattsPerSquareMeterCelsius(this T value) => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatTransferCoefficient? WattsPerSquareMeterCelsius(this T? value) where T : struct => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerSquareMeterKelvin - - /// - public static HeatTransferCoefficient WattsPerSquareMeterKelvin(this T value) => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatTransferCoefficient? WattsPerSquareMeterKelvin(this T? value) where T : struct => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIlluminanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToIlluminanceExtensions.g.cs deleted file mode 100644 index f65660e24d..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIlluminanceExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToIlluminance -{ - public static class NumberToIlluminanceExtensions - { - #region Kilolux - - /// - public static Illuminance Kilolux(this T value) => Illuminance.FromKilolux(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Illuminance? Kilolux(this T? value) where T : struct => Illuminance.FromKilolux(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Lux - - /// - public static Illuminance Lux(this T value) => Illuminance.FromLux(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Illuminance? Lux(this T? value) where T : struct => Illuminance.FromLux(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megalux - - /// - public static Illuminance Megalux(this T value) => Illuminance.FromMegalux(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Illuminance? Megalux(this T? value) where T : struct => Illuminance.FromMegalux(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millilux - - /// - public static Illuminance Millilux(this T value) => Illuminance.FromMillilux(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Illuminance? Millilux(this T? value) where T : struct => Illuminance.FromMillilux(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToInformationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToInformationExtensions.g.cs deleted file mode 100644 index e3e9b1e43e..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToInformationExtensions.g.cs +++ /dev/null @@ -1,335 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToInformation -{ - public static class NumberToInformationExtensions - { - #region Bit - - /// - public static Information Bits(this T value) => Information.FromBits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Bits(this T? value) where T : struct => Information.FromBits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Byte - - /// - public static Information Bytes(this T value) => Information.FromBytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Bytes(this T? value) where T : struct => Information.FromBytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Exabit - - /// - public static Information Exabits(this T value) => Information.FromExabits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Exabits(this T? value) where T : struct => Information.FromExabits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Exabyte - - /// - public static Information Exabytes(this T value) => Information.FromExabytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Exabytes(this T? value) where T : struct => Information.FromExabytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Exbibit - - /// - public static Information Exbibits(this T value) => Information.FromExbibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Exbibits(this T? value) where T : struct => Information.FromExbibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Exbibyte - - /// - public static Information Exbibytes(this T value) => Information.FromExbibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Exbibytes(this T? value) where T : struct => Information.FromExbibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gibibit - - /// - public static Information Gibibits(this T value) => Information.FromGibibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Gibibits(this T? value) where T : struct => Information.FromGibibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gibibyte - - /// - public static Information Gibibytes(this T value) => Information.FromGibibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Gibibytes(this T? value) where T : struct => Information.FromGibibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gigabit - - /// - public static Information Gigabits(this T value) => Information.FromGigabits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Gigabits(this T? value) where T : struct => Information.FromGigabits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gigabyte - - /// - public static Information Gigabytes(this T value) => Information.FromGigabytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Gigabytes(this T? value) where T : struct => Information.FromGigabytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kibibit - - /// - public static Information Kibibits(this T value) => Information.FromKibibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Kibibits(this T? value) where T : struct => Information.FromKibibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kibibyte - - /// - public static Information Kibibytes(this T value) => Information.FromKibibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Kibibytes(this T? value) where T : struct => Information.FromKibibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilobit - - /// - public static Information Kilobits(this T value) => Information.FromKilobits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Kilobits(this T? value) where T : struct => Information.FromKilobits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilobyte - - /// - public static Information Kilobytes(this T value) => Information.FromKilobytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Kilobytes(this T? value) where T : struct => Information.FromKilobytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Mebibit - - /// - public static Information Mebibits(this T value) => Information.FromMebibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Mebibits(this T? value) where T : struct => Information.FromMebibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Mebibyte - - /// - public static Information Mebibytes(this T value) => Information.FromMebibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Mebibytes(this T? value) where T : struct => Information.FromMebibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megabit - - /// - public static Information Megabits(this T value) => Information.FromMegabits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Megabits(this T? value) where T : struct => Information.FromMegabits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megabyte - - /// - public static Information Megabytes(this T value) => Information.FromMegabytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Megabytes(this T? value) where T : struct => Information.FromMegabytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Pebibit - - /// - public static Information Pebibits(this T value) => Information.FromPebibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Pebibits(this T? value) where T : struct => Information.FromPebibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Pebibyte - - /// - public static Information Pebibytes(this T value) => Information.FromPebibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Pebibytes(this T? value) where T : struct => Information.FromPebibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Petabit - - /// - public static Information Petabits(this T value) => Information.FromPetabits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Petabits(this T? value) where T : struct => Information.FromPetabits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Petabyte - - /// - public static Information Petabytes(this T value) => Information.FromPetabytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Petabytes(this T? value) where T : struct => Information.FromPetabytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Tebibit - - /// - public static Information Tebibits(this T value) => Information.FromTebibits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Tebibits(this T? value) where T : struct => Information.FromTebibits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Tebibyte - - /// - public static Information Tebibytes(this T value) => Information.FromTebibytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Tebibytes(this T? value) where T : struct => Information.FromTebibytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Terabit - - /// - public static Information Terabits(this T value) => Information.FromTerabits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Terabits(this T? value) where T : struct => Information.FromTerabits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Terabyte - - /// - public static Information Terabytes(this T value) => Information.FromTerabytes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? Terabytes(this T? value) where T : struct => Information.FromTerabytes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradianceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradianceExtensions.g.cs deleted file mode 100644 index 6102ebb51b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradianceExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToIrradiance -{ - public static class NumberToIrradianceExtensions - { - #region KilowattPerSquareMeter - - /// - public static Irradiance KilowattsPerSquareMeter(this T value) => Irradiance.FromKilowattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiance? KilowattsPerSquareMeter(this T? value) where T : struct => Irradiance.FromKilowattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerSquareMeter - - /// - public static Irradiance WattsPerSquareMeter(this T value) => Irradiance.FromWattsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiance? WattsPerSquareMeter(this T? value) where T : struct => Irradiance.FromWattsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradiationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradiationExtensions.g.cs deleted file mode 100644 index 790e51aea5..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToIrradiationExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToIrradiation -{ - public static class NumberToIrradiationExtensions - { - #region JoulePerSquareMeter - - /// - public static Irradiation JoulesPerSquareMeter(this T value) => Irradiation.FromJoulesPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiation? JoulesPerSquareMeter(this T? value) where T : struct => Irradiation.FromJoulesPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattHourPerSquareMeter - - /// - public static Irradiation KilowattHoursPerSquareMeter(this T value) => Irradiation.FromKilowattHoursPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiation? KilowattHoursPerSquareMeter(this T? value) where T : struct => Irradiation.FromKilowattHoursPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattHourPerSquareMeter - - /// - public static Irradiation WattHoursPerSquareMeter(this T value) => Irradiation.FromWattHoursPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiation? WattHoursPerSquareMeter(this T? value) where T : struct => Irradiation.FromWattHoursPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToKinematicViscosityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToKinematicViscosityExtensions.g.cs deleted file mode 100644 index ba6654d1d2..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToKinematicViscosityExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToKinematicViscosity -{ - public static class NumberToKinematicViscosityExtensions - { - #region Centistokes - - /// - public static KinematicViscosity Centistokes(this T value) => KinematicViscosity.FromCentistokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Centistokes(this T? value) where T : struct => KinematicViscosity.FromCentistokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decistokes - - /// - public static KinematicViscosity Decistokes(this T value) => KinematicViscosity.FromDecistokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Decistokes(this T? value) where T : struct => KinematicViscosity.FromDecistokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilostokes - - /// - public static KinematicViscosity Kilostokes(this T value) => KinematicViscosity.FromKilostokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Kilostokes(this T? value) where T : struct => KinematicViscosity.FromKilostokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microstokes - - /// - public static KinematicViscosity Microstokes(this T value) => KinematicViscosity.FromMicrostokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Microstokes(this T? value) where T : struct => KinematicViscosity.FromMicrostokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millistokes - - /// - public static KinematicViscosity Millistokes(this T value) => KinematicViscosity.FromMillistokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Millistokes(this T? value) where T : struct => KinematicViscosity.FromMillistokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanostokes - - /// - public static KinematicViscosity Nanostokes(this T value) => KinematicViscosity.FromNanostokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Nanostokes(this T? value) where T : struct => KinematicViscosity.FromNanostokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMeterPerSecond - - /// - public static KinematicViscosity SquareMetersPerSecond(this T value) => KinematicViscosity.FromSquareMetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? SquareMetersPerSecond(this T? value) where T : struct => KinematicViscosity.FromSquareMetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Stokes - - /// - public static KinematicViscosity Stokes(this T value) => KinematicViscosity.FromStokes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? Stokes(this T? value) where T : struct => KinematicViscosity.FromStokes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLapseRateExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLapseRateExtensions.g.cs deleted file mode 100644 index 591ef48585..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLapseRateExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLapseRate -{ - public static class NumberToLapseRateExtensions - { - #region DegreeCelsiusPerKilometer - - /// - public static LapseRate DegreesCelciusPerKilometer(this T value) => LapseRate.FromDegreesCelciusPerKilometer(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LapseRate? DegreesCelciusPerKilometer(this T? value) where T : struct => LapseRate.FromDegreesCelciusPerKilometer(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLengthExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLengthExtensions.g.cs deleted file mode 100644 index 0b2b14e3a0..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLengthExtensions.g.cs +++ /dev/null @@ -1,291 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLength -{ - public static class NumberToLengthExtensions - { - #region Centimeter - - /// - public static Length Centimeters(this T value) => Length.FromCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Centimeters(this T? value) where T : struct => Length.FromCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decimeter - - /// - public static Length Decimeters(this T value) => Length.FromDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Decimeters(this T? value) where T : struct => Length.FromDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DtpPica - - /// - public static Length DtpPicas(this T value) => Length.FromDtpPicas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? DtpPicas(this T? value) where T : struct => Length.FromDtpPicas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DtpPoint - - /// - public static Length DtpPoints(this T value) => Length.FromDtpPoints(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? DtpPoints(this T? value) where T : struct => Length.FromDtpPoints(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Fathom - - /// - public static Length Fathoms(this T value) => Length.FromFathoms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Fathoms(this T? value) where T : struct => Length.FromFathoms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Foot - - /// - public static Length Feet(this T value) => Length.FromFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Feet(this T? value) where T : struct => Length.FromFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Inch - - /// - public static Length Inches(this T value) => Length.FromInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Inches(this T? value) where T : struct => Length.FromInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilometer - - /// - public static Length Kilometers(this T value) => Length.FromKilometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Kilometers(this T? value) where T : struct => Length.FromKilometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Meter - - /// - public static Length Meters(this T value) => Length.FromMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Meters(this T? value) where T : struct => Length.FromMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microinch - - /// - public static Length Microinches(this T value) => Length.FromMicroinches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Microinches(this T? value) where T : struct => Length.FromMicroinches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Micrometer - - /// - public static Length Micrometers(this T value) => Length.FromMicrometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Micrometers(this T? value) where T : struct => Length.FromMicrometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Mil - - /// - public static Length Mils(this T value) => Length.FromMils(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Mils(this T? value) where T : struct => Length.FromMils(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Mile - - /// - public static Length Miles(this T value) => Length.FromMiles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Miles(this T? value) where T : struct => Length.FromMiles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millimeter - - /// - public static Length Millimeters(this T value) => Length.FromMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Millimeters(this T? value) where T : struct => Length.FromMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanometer - - /// - public static Length Nanometers(this T value) => Length.FromNanometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Nanometers(this T? value) where T : struct => Length.FromNanometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NauticalMile - - /// - public static Length NauticalMiles(this T value) => Length.FromNauticalMiles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? NauticalMiles(this T? value) where T : struct => Length.FromNauticalMiles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PrinterPica - - /// - public static Length PrinterPicas(this T value) => Length.FromPrinterPicas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? PrinterPicas(this T? value) where T : struct => Length.FromPrinterPicas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PrinterPoint - - /// - public static Length PrinterPoints(this T value) => Length.FromPrinterPoints(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? PrinterPoints(this T? value) where T : struct => Length.FromPrinterPoints(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Shackle - - /// - public static Length Shackles(this T value) => Length.FromShackles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Shackles(this T? value) where T : struct => Length.FromShackles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Twip - - /// - public static Length Twips(this T value) => Length.FromTwips(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Twips(this T? value) where T : struct => Length.FromTwips(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsSurveyFoot - - /// - public static Length UsSurveyFeet(this T value) => Length.FromUsSurveyFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? UsSurveyFeet(this T? value) where T : struct => Length.FromUsSurveyFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Yard - - /// - public static Length Yards(this T value) => Length.FromYards(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? Yards(this T? value) where T : struct => Length.FromYards(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLevelExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLevelExtensions.g.cs deleted file mode 100644 index f0d7aed5c8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLevelExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLevel -{ - public static class NumberToLevelExtensions - { - #region Decibel - - /// - public static Level Decibels(this T value) => Level.FromDecibels(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Level? Decibels(this T? value) where T : struct => Level.FromDecibels(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Neper - - /// - public static Level Nepers(this T value) => Level.FromNepers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Level? Nepers(this T? value) where T : struct => Level.FromNepers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLinearDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLinearDensityExtensions.g.cs deleted file mode 100644 index 9481175332..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLinearDensityExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLinearDensity -{ - public static class NumberToLinearDensityExtensions - { - #region GramPerMeter - - /// - public static LinearDensity GramsPerMeter(this T value) => LinearDensity.FromGramsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LinearDensity? GramsPerMeter(this T? value) where T : struct => LinearDensity.FromGramsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerMeter - - /// - public static LinearDensity KilogramsPerMeter(this T value) => LinearDensity.FromKilogramsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LinearDensity? KilogramsPerMeter(this T? value) where T : struct => LinearDensity.FromKilogramsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerFoot - - /// - public static LinearDensity PoundsPerFoot(this T value) => LinearDensity.FromPoundsPerFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LinearDensity? PoundsPerFoot(this T? value) where T : struct => LinearDensity.FromPoundsPerFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousFluxExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousFluxExtensions.g.cs deleted file mode 100644 index 3db0da00d8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousFluxExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLuminousFlux -{ - public static class NumberToLuminousFluxExtensions - { - #region Lumen - - /// - public static LuminousFlux Lumens(this T value) => LuminousFlux.FromLumens(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LuminousFlux? Lumens(this T? value) where T : struct => LuminousFlux.FromLumens(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousIntensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousIntensityExtensions.g.cs deleted file mode 100644 index 79c9c9cd1b..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToLuminousIntensityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToLuminousIntensity -{ - public static class NumberToLuminousIntensityExtensions - { - #region Candela - - /// - public static LuminousIntensity Candela(this T value) => LuminousIntensity.FromCandela(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LuminousIntensity? Candela(this T? value) where T : struct => LuminousIntensity.FromCandela(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFieldExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFieldExtensions.g.cs deleted file mode 100644 index d638247642..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFieldExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMagneticField -{ - public static class NumberToMagneticFieldExtensions - { - #region Microtesla - - /// - public static MagneticField Microteslas(this T value) => MagneticField.FromMicroteslas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticField? Microteslas(this T? value) where T : struct => MagneticField.FromMicroteslas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millitesla - - /// - public static MagneticField Milliteslas(this T value) => MagneticField.FromMilliteslas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticField? Milliteslas(this T? value) where T : struct => MagneticField.FromMilliteslas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanotesla - - /// - public static MagneticField Nanoteslas(this T value) => MagneticField.FromNanoteslas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticField? Nanoteslas(this T? value) where T : struct => MagneticField.FromNanoteslas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Tesla - - /// - public static MagneticField Teslas(this T value) => MagneticField.FromTeslas(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticField? Teslas(this T? value) where T : struct => MagneticField.FromTeslas(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFluxExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFluxExtensions.g.cs deleted file mode 100644 index 935ecb2375..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagneticFluxExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMagneticFlux -{ - public static class NumberToMagneticFluxExtensions - { - #region Weber - - /// - public static MagneticFlux Webers(this T value) => MagneticFlux.FromWebers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticFlux? Webers(this T? value) where T : struct => MagneticFlux.FromWebers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagnetizationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagnetizationExtensions.g.cs deleted file mode 100644 index cce5daf093..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMagnetizationExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMagnetization -{ - public static class NumberToMagnetizationExtensions - { - #region AmperePerMeter - - /// - public static Magnetization AmperesPerMeter(this T value) => Magnetization.FromAmperesPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Magnetization? AmperesPerMeter(this T? value) where T : struct => Magnetization.FromAmperesPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassExtensions.g.cs deleted file mode 100644 index 05dffe404f..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassExtensions.g.cs +++ /dev/null @@ -1,291 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMass -{ - public static class NumberToMassExtensions - { - #region Centigram - - /// - public static Mass Centigrams(this T value) => Mass.FromCentigrams(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Centigrams(this T? value) where T : struct => Mass.FromCentigrams(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decagram - - /// - public static Mass Decagrams(this T value) => Mass.FromDecagrams(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Decagrams(this T? value) where T : struct => Mass.FromDecagrams(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decigram - - /// - public static Mass Decigrams(this T value) => Mass.FromDecigrams(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Decigrams(this T? value) where T : struct => Mass.FromDecigrams(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gram - - /// - public static Mass Grams(this T value) => Mass.FromGrams(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Grams(this T? value) where T : struct => Mass.FromGrams(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hectogram - - /// - public static Mass Hectograms(this T value) => Mass.FromHectograms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Hectograms(this T? value) where T : struct => Mass.FromHectograms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilogram - - /// - public static Mass Kilograms(this T value) => Mass.FromKilograms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Kilograms(this T? value) where T : struct => Mass.FromKilograms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilopound - - /// - public static Mass Kilopounds(this T value) => Mass.FromKilopounds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Kilopounds(this T? value) where T : struct => Mass.FromKilopounds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilotonne - - /// - public static Mass Kilotonnes(this T value) => Mass.FromKilotonnes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Kilotonnes(this T? value) where T : struct => Mass.FromKilotonnes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LongHundredweight - - /// - public static Mass LongHundredweight(this T value) => Mass.FromLongHundredweight(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? LongHundredweight(this T? value) where T : struct => Mass.FromLongHundredweight(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LongTon - - /// - public static Mass LongTons(this T value) => Mass.FromLongTons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? LongTons(this T? value) where T : struct => Mass.FromLongTons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megapound - - /// - public static Mass Megapounds(this T value) => Mass.FromMegapounds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Megapounds(this T? value) where T : struct => Mass.FromMegapounds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megatonne - - /// - public static Mass Megatonnes(this T value) => Mass.FromMegatonnes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Megatonnes(this T? value) where T : struct => Mass.FromMegatonnes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microgram - - /// - public static Mass Micrograms(this T value) => Mass.FromMicrograms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Micrograms(this T? value) where T : struct => Mass.FromMicrograms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milligram - - /// - public static Mass Milligrams(this T value) => Mass.FromMilligrams(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Milligrams(this T? value) where T : struct => Mass.FromMilligrams(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanogram - - /// - public static Mass Nanograms(this T value) => Mass.FromNanograms(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Nanograms(this T? value) where T : struct => Mass.FromNanograms(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Ounce - - /// - public static Mass Ounces(this T value) => Mass.FromOunces(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Ounces(this T? value) where T : struct => Mass.FromOunces(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Pound - - /// - public static Mass Pounds(this T value) => Mass.FromPounds(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Pounds(this T? value) where T : struct => Mass.FromPounds(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ShortHundredweight - - /// - public static Mass ShortHundredweight(this T value) => Mass.FromShortHundredweight(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? ShortHundredweight(this T? value) where T : struct => Mass.FromShortHundredweight(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ShortTon - - /// - public static Mass ShortTons(this T value) => Mass.FromShortTons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? ShortTons(this T? value) where T : struct => Mass.FromShortTons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Slug - - /// - public static Mass Slugs(this T value) => Mass.FromSlugs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Slugs(this T? value) where T : struct => Mass.FromSlugs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Stone - - /// - public static Mass Stone(this T value) => Mass.FromStone(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Stone(this T? value) where T : struct => Mass.FromStone(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Tonne - - /// - public static Mass Tonnes(this T value) => Mass.FromTonnes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? Tonnes(this T? value) where T : struct => Mass.FromTonnes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFlowExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFlowExtensions.g.cs deleted file mode 100644 index f5b063b291..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFlowExtensions.g.cs +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMassFlow -{ - public static class NumberToMassFlowExtensions - { - #region CentigramPerSecond - - /// - public static MassFlow CentigramsPerSecond(this T value) => MassFlow.FromCentigramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? CentigramsPerSecond(this T? value) where T : struct => MassFlow.FromCentigramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecagramPerSecond - - /// - public static MassFlow DecagramsPerSecond(this T value) => MassFlow.FromDecagramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? DecagramsPerSecond(this T? value) where T : struct => MassFlow.FromDecagramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecigramPerSecond - - /// - public static MassFlow DecigramsPerSecond(this T value) => MassFlow.FromDecigramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? DecigramsPerSecond(this T? value) where T : struct => MassFlow.FromDecigramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerSecond - - /// - public static MassFlow GramsPerSecond(this T value) => MassFlow.FromGramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? GramsPerSecond(this T? value) where T : struct => MassFlow.FromGramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HectogramPerSecond - - /// - public static MassFlow HectogramsPerSecond(this T value) => MassFlow.FromHectogramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? HectogramsPerSecond(this T? value) where T : struct => MassFlow.FromHectogramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerHour - - /// - public static MassFlow KilogramsPerHour(this T value) => MassFlow.FromKilogramsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? KilogramsPerHour(this T? value) where T : struct => MassFlow.FromKilogramsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerMinute - - /// - public static MassFlow KilogramsPerMinute(this T value) => MassFlow.FromKilogramsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? KilogramsPerMinute(this T? value) where T : struct => MassFlow.FromKilogramsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerSecond - - /// - public static MassFlow KilogramsPerSecond(this T value) => MassFlow.FromKilogramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? KilogramsPerSecond(this T? value) where T : struct => MassFlow.FromKilogramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapoundPerHour - - /// - public static MassFlow MegapoundsPerHour(this T value) => MassFlow.FromMegapoundsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? MegapoundsPerHour(this T? value) where T : struct => MassFlow.FromMegapoundsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapoundPerMinute - - /// - public static MassFlow MegapoundsPerMinute(this T value) => MassFlow.FromMegapoundsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? MegapoundsPerMinute(this T? value) where T : struct => MassFlow.FromMegapoundsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrogramPerSecond - - /// - public static MassFlow MicrogramsPerSecond(this T value) => MassFlow.FromMicrogramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? MicrogramsPerSecond(this T? value) where T : struct => MassFlow.FromMicrogramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerSecond - - /// - public static MassFlow MilligramsPerSecond(this T value) => MassFlow.FromMilligramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? MilligramsPerSecond(this T? value) where T : struct => MassFlow.FromMilligramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanogramPerSecond - - /// - public static MassFlow NanogramsPerSecond(this T value) => MassFlow.FromNanogramsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? NanogramsPerSecond(this T? value) where T : struct => MassFlow.FromNanogramsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerHour - - /// - public static MassFlow PoundsPerHour(this T value) => MassFlow.FromPoundsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? PoundsPerHour(this T? value) where T : struct => MassFlow.FromPoundsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerMinute - - /// - public static MassFlow PoundsPerMinute(this T value) => MassFlow.FromPoundsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? PoundsPerMinute(this T? value) where T : struct => MassFlow.FromPoundsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ShortTonPerHour - - /// - public static MassFlow ShortTonsPerHour(this T value) => MassFlow.FromShortTonsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? ShortTonsPerHour(this T? value) where T : struct => MassFlow.FromShortTonsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonnePerDay - - /// - public static MassFlow TonnesPerDay(this T value) => MassFlow.FromTonnesPerDay(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? TonnesPerDay(this T? value) where T : struct => MassFlow.FromTonnesPerDay(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonnePerHour - - /// - public static MassFlow TonnesPerHour(this T value) => MassFlow.FromTonnesPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? TonnesPerHour(this T? value) where T : struct => MassFlow.FromTonnesPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFluxExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFluxExtensions.g.cs deleted file mode 100644 index 08731e83a2..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassFluxExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMassFlux -{ - public static class NumberToMassFluxExtensions - { - #region GramPerSecondPerSquareMeter - - /// - public static MassFlux GramsPerSecondPerSquareMeter(this T value) => MassFlux.FromGramsPerSecondPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlux? GramsPerSecondPerSquareMeter(this T? value) where T : struct => MassFlux.FromGramsPerSecondPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerSecondPerSquareMeter - - /// - public static MassFlux KilogramsPerSecondPerSquareMeter(this T value) => MassFlux.FromKilogramsPerSecondPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlux? KilogramsPerSecondPerSquareMeter(this T? value) where T : struct => MassFlux.FromKilogramsPerSecondPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassMomentOfInertiaExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassMomentOfInertiaExtensions.g.cs deleted file mode 100644 index 71db827e43..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMassMomentOfInertiaExtensions.g.cs +++ /dev/null @@ -1,357 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMassMomentOfInertia -{ - public static class NumberToMassMomentOfInertiaExtensions - { - #region GramSquareCentimeter - - /// - public static MassMomentOfInertia GramSquareCentimeters(this T value) => MassMomentOfInertia.FromGramSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? GramSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromGramSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramSquareDecimeter - - /// - public static MassMomentOfInertia GramSquareDecimeters(this T value) => MassMomentOfInertia.FromGramSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? GramSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromGramSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramSquareMeter - - /// - public static MassMomentOfInertia GramSquareMeters(this T value) => MassMomentOfInertia.FromGramSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? GramSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromGramSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramSquareMillimeter - - /// - public static MassMomentOfInertia GramSquareMillimeters(this T value) => MassMomentOfInertia.FromGramSquareMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? GramSquareMillimeters(this T? value) where T : struct => MassMomentOfInertia.FromGramSquareMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramSquareCentimeter - - /// - public static MassMomentOfInertia KilogramSquareCentimeters(this T value) => MassMomentOfInertia.FromKilogramSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilogramSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilogramSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramSquareDecimeter - - /// - public static MassMomentOfInertia KilogramSquareDecimeters(this T value) => MassMomentOfInertia.FromKilogramSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilogramSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilogramSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramSquareMeter - - /// - public static MassMomentOfInertia KilogramSquareMeters(this T value) => MassMomentOfInertia.FromKilogramSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilogramSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromKilogramSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramSquareMillimeter - - /// - public static MassMomentOfInertia KilogramSquareMillimeters(this T value) => MassMomentOfInertia.FromKilogramSquareMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilogramSquareMillimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilogramSquareMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilotonneSquareCentimeter - - /// - public static MassMomentOfInertia KilotonneSquareCentimeters(this T value) => MassMomentOfInertia.FromKilotonneSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilotonneSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilotonneSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilotonneSquareDecimeter - - /// - public static MassMomentOfInertia KilotonneSquareDecimeters(this T value) => MassMomentOfInertia.FromKilotonneSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilotonneSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilotonneSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilotonneSquareMeter - - /// - public static MassMomentOfInertia KilotonneSquareMeters(this T value) => MassMomentOfInertia.FromKilotonneSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilotonneSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromKilotonneSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilotonneSquareMilimeter - - /// - public static MassMomentOfInertia KilotonneSquareMilimeters(this T value) => MassMomentOfInertia.FromKilotonneSquareMilimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? KilotonneSquareMilimeters(this T? value) where T : struct => MassMomentOfInertia.FromKilotonneSquareMilimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegatonneSquareCentimeter - - /// - public static MassMomentOfInertia MegatonneSquareCentimeters(this T value) => MassMomentOfInertia.FromMegatonneSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MegatonneSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromMegatonneSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegatonneSquareDecimeter - - /// - public static MassMomentOfInertia MegatonneSquareDecimeters(this T value) => MassMomentOfInertia.FromMegatonneSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MegatonneSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromMegatonneSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegatonneSquareMeter - - /// - public static MassMomentOfInertia MegatonneSquareMeters(this T value) => MassMomentOfInertia.FromMegatonneSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MegatonneSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromMegatonneSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegatonneSquareMilimeter - - /// - public static MassMomentOfInertia MegatonneSquareMilimeters(this T value) => MassMomentOfInertia.FromMegatonneSquareMilimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MegatonneSquareMilimeters(this T? value) where T : struct => MassMomentOfInertia.FromMegatonneSquareMilimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramSquareCentimeter - - /// - public static MassMomentOfInertia MilligramSquareCentimeters(this T value) => MassMomentOfInertia.FromMilligramSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MilligramSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromMilligramSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramSquareDecimeter - - /// - public static MassMomentOfInertia MilligramSquareDecimeters(this T value) => MassMomentOfInertia.FromMilligramSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MilligramSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromMilligramSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramSquareMeter - - /// - public static MassMomentOfInertia MilligramSquareMeters(this T value) => MassMomentOfInertia.FromMilligramSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MilligramSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromMilligramSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramSquareMillimeter - - /// - public static MassMomentOfInertia MilligramSquareMillimeters(this T value) => MassMomentOfInertia.FromMilligramSquareMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? MilligramSquareMillimeters(this T? value) where T : struct => MassMomentOfInertia.FromMilligramSquareMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundSquareFoot - - /// - public static MassMomentOfInertia PoundSquareFeet(this T value) => MassMomentOfInertia.FromPoundSquareFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? PoundSquareFeet(this T? value) where T : struct => MassMomentOfInertia.FromPoundSquareFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundSquareInch - - /// - public static MassMomentOfInertia PoundSquareInches(this T value) => MassMomentOfInertia.FromPoundSquareInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? PoundSquareInches(this T? value) where T : struct => MassMomentOfInertia.FromPoundSquareInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SlugSquareFoot - - /// - public static MassMomentOfInertia SlugSquareFeet(this T value) => MassMomentOfInertia.FromSlugSquareFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? SlugSquareFeet(this T? value) where T : struct => MassMomentOfInertia.FromSlugSquareFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SlugSquareInch - - /// - public static MassMomentOfInertia SlugSquareInches(this T value) => MassMomentOfInertia.FromSlugSquareInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? SlugSquareInches(this T? value) where T : struct => MassMomentOfInertia.FromSlugSquareInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneSquareCentimeter - - /// - public static MassMomentOfInertia TonneSquareCentimeters(this T value) => MassMomentOfInertia.FromTonneSquareCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? TonneSquareCentimeters(this T? value) where T : struct => MassMomentOfInertia.FromTonneSquareCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneSquareDecimeter - - /// - public static MassMomentOfInertia TonneSquareDecimeters(this T value) => MassMomentOfInertia.FromTonneSquareDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? TonneSquareDecimeters(this T? value) where T : struct => MassMomentOfInertia.FromTonneSquareDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneSquareMeter - - /// - public static MassMomentOfInertia TonneSquareMeters(this T value) => MassMomentOfInertia.FromTonneSquareMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? TonneSquareMeters(this T? value) where T : struct => MassMomentOfInertia.FromTonneSquareMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneSquareMilimeter - - /// - public static MassMomentOfInertia TonneSquareMilimeters(this T value) => MassMomentOfInertia.FromTonneSquareMilimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? TonneSquareMilimeters(this T? value) where T : struct => MassMomentOfInertia.FromTonneSquareMilimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEnergyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEnergyExtensions.g.cs deleted file mode 100644 index bd21a01cfe..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEnergyExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMolarEnergy -{ - public static class NumberToMolarEnergyExtensions - { - #region JoulePerMole - - /// - public static MolarEnergy JoulesPerMole(this T value) => MolarEnergy.FromJoulesPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEnergy? JoulesPerMole(this T? value) where T : struct => MolarEnergy.FromJoulesPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerMole - - /// - public static MolarEnergy KilojoulesPerMole(this T value) => MolarEnergy.FromKilojoulesPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEnergy? KilojoulesPerMole(this T? value) where T : struct => MolarEnergy.FromKilojoulesPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerMole - - /// - public static MolarEnergy MegajoulesPerMole(this T value) => MolarEnergy.FromMegajoulesPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEnergy? MegajoulesPerMole(this T? value) where T : struct => MolarEnergy.FromMegajoulesPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEntropyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEntropyExtensions.g.cs deleted file mode 100644 index 1585ae6298..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarEntropyExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMolarEntropy -{ - public static class NumberToMolarEntropyExtensions - { - #region JoulePerMoleKelvin - - /// - public static MolarEntropy JoulesPerMoleKelvin(this T value) => MolarEntropy.FromJoulesPerMoleKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEntropy? JoulesPerMoleKelvin(this T? value) where T : struct => MolarEntropy.FromJoulesPerMoleKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerMoleKelvin - - /// - public static MolarEntropy KilojoulesPerMoleKelvin(this T value) => MolarEntropy.FromKilojoulesPerMoleKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEntropy? KilojoulesPerMoleKelvin(this T? value) where T : struct => MolarEntropy.FromKilojoulesPerMoleKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerMoleKelvin - - /// - public static MolarEntropy MegajoulesPerMoleKelvin(this T value) => MolarEntropy.FromMegajoulesPerMoleKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEntropy? MegajoulesPerMoleKelvin(this T? value) where T : struct => MolarEntropy.FromMegajoulesPerMoleKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarMassExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarMassExtensions.g.cs deleted file mode 100644 index bde7d51d10..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarMassExtensions.g.cs +++ /dev/null @@ -1,181 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMolarMass -{ - public static class NumberToMolarMassExtensions - { - #region CentigramPerMole - - /// - public static MolarMass CentigramsPerMole(this T value) => MolarMass.FromCentigramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? CentigramsPerMole(this T? value) where T : struct => MolarMass.FromCentigramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecagramPerMole - - /// - public static MolarMass DecagramsPerMole(this T value) => MolarMass.FromDecagramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? DecagramsPerMole(this T? value) where T : struct => MolarMass.FromDecagramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecigramPerMole - - /// - public static MolarMass DecigramsPerMole(this T value) => MolarMass.FromDecigramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? DecigramsPerMole(this T? value) where T : struct => MolarMass.FromDecigramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GramPerMole - - /// - public static MolarMass GramsPerMole(this T value) => MolarMass.FromGramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? GramsPerMole(this T? value) where T : struct => MolarMass.FromGramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HectogramPerMole - - /// - public static MolarMass HectogramsPerMole(this T value) => MolarMass.FromHectogramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? HectogramsPerMole(this T? value) where T : struct => MolarMass.FromHectogramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramPerMole - - /// - public static MolarMass KilogramsPerMole(this T value) => MolarMass.FromKilogramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? KilogramsPerMole(this T? value) where T : struct => MolarMass.FromKilogramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundPerMole - - /// - public static MolarMass KilopoundsPerMole(this T value) => MolarMass.FromKilopoundsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? KilopoundsPerMole(this T? value) where T : struct => MolarMass.FromKilopoundsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapoundPerMole - - /// - public static MolarMass MegapoundsPerMole(this T value) => MolarMass.FromMegapoundsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? MegapoundsPerMole(this T? value) where T : struct => MolarMass.FromMegapoundsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrogramPerMole - - /// - public static MolarMass MicrogramsPerMole(this T value) => MolarMass.FromMicrogramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? MicrogramsPerMole(this T? value) where T : struct => MolarMass.FromMicrogramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilligramPerMole - - /// - public static MolarMass MilligramsPerMole(this T value) => MolarMass.FromMilligramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? MilligramsPerMole(this T? value) where T : struct => MolarMass.FromMilligramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanogramPerMole - - /// - public static MolarMass NanogramsPerMole(this T value) => MolarMass.FromNanogramsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? NanogramsPerMole(this T? value) where T : struct => MolarMass.FromNanogramsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerMole - - /// - public static MolarMass PoundsPerMole(this T value) => MolarMass.FromPoundsPerMole(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? PoundsPerMole(this T? value) where T : struct => MolarMass.FromPoundsPerMole(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarityExtensions.g.cs deleted file mode 100644 index e8a9e7d2e1..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToMolarityExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToMolarity -{ - public static class NumberToMolarityExtensions - { - #region CentimolesPerLiter - - /// - public static Molarity CentimolesPerLiter(this T value) => Molarity.FromCentimolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? CentimolesPerLiter(this T? value) where T : struct => Molarity.FromCentimolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecimolesPerLiter - - /// - public static Molarity DecimolesPerLiter(this T value) => Molarity.FromDecimolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? DecimolesPerLiter(this T? value) where T : struct => Molarity.FromDecimolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicromolesPerLiter - - /// - public static Molarity MicromolesPerLiter(this T value) => Molarity.FromMicromolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? MicromolesPerLiter(this T? value) where T : struct => Molarity.FromMicromolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimolesPerLiter - - /// - public static Molarity MillimolesPerLiter(this T value) => Molarity.FromMillimolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? MillimolesPerLiter(this T? value) where T : struct => Molarity.FromMillimolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MolesPerCubicMeter - - /// - public static Molarity MolesPerCubicMeter(this T value) => Molarity.FromMolesPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? MolesPerCubicMeter(this T? value) where T : struct => Molarity.FromMolesPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MolesPerLiter - - /// - public static Molarity MolesPerLiter(this T value) => Molarity.FromMolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? MolesPerLiter(this T? value) where T : struct => Molarity.FromMolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanomolesPerLiter - - /// - public static Molarity NanomolesPerLiter(this T value) => Molarity.FromNanomolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? NanomolesPerLiter(this T? value) where T : struct => Molarity.FromNanomolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicomolesPerLiter - - /// - public static Molarity PicomolesPerLiter(this T value) => Molarity.FromPicomolesPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? PicomolesPerLiter(this T? value) where T : struct => Molarity.FromPicomolesPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermeabilityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermeabilityExtensions.g.cs deleted file mode 100644 index e098fc24ea..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermeabilityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPermeability -{ - public static class NumberToPermeabilityExtensions - { - #region HenryPerMeter - - /// - public static Permeability HenriesPerMeter(this T value) => Permeability.FromHenriesPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Permeability? HenriesPerMeter(this T? value) where T : struct => Permeability.FromHenriesPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermittivityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermittivityExtensions.g.cs deleted file mode 100644 index 8744ae9a5f..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPermittivityExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPermittivity -{ - public static class NumberToPermittivityExtensions - { - #region FaradPerMeter - - /// - public static Permittivity FaradsPerMeter(this T value) => Permittivity.FromFaradsPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Permittivity? FaradsPerMeter(this T? value) where T : struct => Permittivity.FromFaradsPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerDensityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerDensityExtensions.g.cs deleted file mode 100644 index fdf6c889f3..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerDensityExtensions.g.cs +++ /dev/null @@ -1,533 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPowerDensity -{ - public static class NumberToPowerDensityExtensions - { - #region DecawattPerCubicFoot - - /// - public static PowerDensity DecawattsPerCubicFoot(this T value) => PowerDensity.FromDecawattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DecawattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromDecawattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecawattPerCubicInch - - /// - public static PowerDensity DecawattsPerCubicInch(this T value) => PowerDensity.FromDecawattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DecawattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromDecawattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecawattPerCubicMeter - - /// - public static PowerDensity DecawattsPerCubicMeter(this T value) => PowerDensity.FromDecawattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DecawattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromDecawattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecawattPerLiter - - /// - public static PowerDensity DecawattsPerLiter(this T value) => PowerDensity.FromDecawattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DecawattsPerLiter(this T? value) where T : struct => PowerDensity.FromDecawattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciwattPerCubicFoot - - /// - public static PowerDensity DeciwattsPerCubicFoot(this T value) => PowerDensity.FromDeciwattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DeciwattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromDeciwattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciwattPerCubicInch - - /// - public static PowerDensity DeciwattsPerCubicInch(this T value) => PowerDensity.FromDeciwattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DeciwattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromDeciwattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciwattPerCubicMeter - - /// - public static PowerDensity DeciwattsPerCubicMeter(this T value) => PowerDensity.FromDeciwattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DeciwattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromDeciwattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciwattPerLiter - - /// - public static PowerDensity DeciwattsPerLiter(this T value) => PowerDensity.FromDeciwattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? DeciwattsPerLiter(this T? value) where T : struct => PowerDensity.FromDeciwattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigawattPerCubicFoot - - /// - public static PowerDensity GigawattsPerCubicFoot(this T value) => PowerDensity.FromGigawattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? GigawattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromGigawattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigawattPerCubicInch - - /// - public static PowerDensity GigawattsPerCubicInch(this T value) => PowerDensity.FromGigawattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? GigawattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromGigawattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigawattPerCubicMeter - - /// - public static PowerDensity GigawattsPerCubicMeter(this T value) => PowerDensity.FromGigawattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? GigawattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromGigawattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region GigawattPerLiter - - /// - public static PowerDensity GigawattsPerLiter(this T value) => PowerDensity.FromGigawattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? GigawattsPerLiter(this T? value) where T : struct => PowerDensity.FromGigawattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattPerCubicFoot - - /// - public static PowerDensity KilowattsPerCubicFoot(this T value) => PowerDensity.FromKilowattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? KilowattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromKilowattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattPerCubicInch - - /// - public static PowerDensity KilowattsPerCubicInch(this T value) => PowerDensity.FromKilowattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? KilowattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromKilowattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattPerCubicMeter - - /// - public static PowerDensity KilowattsPerCubicMeter(this T value) => PowerDensity.FromKilowattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? KilowattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromKilowattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattPerLiter - - /// - public static PowerDensity KilowattsPerLiter(this T value) => PowerDensity.FromKilowattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? KilowattsPerLiter(this T? value) where T : struct => PowerDensity.FromKilowattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattPerCubicFoot - - /// - public static PowerDensity MegawattsPerCubicFoot(this T value) => PowerDensity.FromMegawattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MegawattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromMegawattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattPerCubicInch - - /// - public static PowerDensity MegawattsPerCubicInch(this T value) => PowerDensity.FromMegawattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MegawattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromMegawattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattPerCubicMeter - - /// - public static PowerDensity MegawattsPerCubicMeter(this T value) => PowerDensity.FromMegawattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MegawattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromMegawattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattPerLiter - - /// - public static PowerDensity MegawattsPerLiter(this T value) => PowerDensity.FromMegawattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MegawattsPerLiter(this T? value) where T : struct => PowerDensity.FromMegawattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrowattPerCubicFoot - - /// - public static PowerDensity MicrowattsPerCubicFoot(this T value) => PowerDensity.FromMicrowattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MicrowattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromMicrowattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrowattPerCubicInch - - /// - public static PowerDensity MicrowattsPerCubicInch(this T value) => PowerDensity.FromMicrowattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MicrowattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromMicrowattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrowattPerCubicMeter - - /// - public static PowerDensity MicrowattsPerCubicMeter(this T value) => PowerDensity.FromMicrowattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MicrowattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromMicrowattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrowattPerLiter - - /// - public static PowerDensity MicrowattsPerLiter(this T value) => PowerDensity.FromMicrowattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MicrowattsPerLiter(this T? value) where T : struct => PowerDensity.FromMicrowattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliwattPerCubicFoot - - /// - public static PowerDensity MilliwattsPerCubicFoot(this T value) => PowerDensity.FromMilliwattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MilliwattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromMilliwattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliwattPerCubicInch - - /// - public static PowerDensity MilliwattsPerCubicInch(this T value) => PowerDensity.FromMilliwattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MilliwattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromMilliwattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliwattPerCubicMeter - - /// - public static PowerDensity MilliwattsPerCubicMeter(this T value) => PowerDensity.FromMilliwattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MilliwattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromMilliwattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliwattPerLiter - - /// - public static PowerDensity MilliwattsPerLiter(this T value) => PowerDensity.FromMilliwattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? MilliwattsPerLiter(this T? value) where T : struct => PowerDensity.FromMilliwattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanowattPerCubicFoot - - /// - public static PowerDensity NanowattsPerCubicFoot(this T value) => PowerDensity.FromNanowattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? NanowattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromNanowattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanowattPerCubicInch - - /// - public static PowerDensity NanowattsPerCubicInch(this T value) => PowerDensity.FromNanowattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? NanowattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromNanowattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanowattPerCubicMeter - - /// - public static PowerDensity NanowattsPerCubicMeter(this T value) => PowerDensity.FromNanowattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? NanowattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromNanowattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanowattPerLiter - - /// - public static PowerDensity NanowattsPerLiter(this T value) => PowerDensity.FromNanowattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? NanowattsPerLiter(this T? value) where T : struct => PowerDensity.FromNanowattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicowattPerCubicFoot - - /// - public static PowerDensity PicowattsPerCubicFoot(this T value) => PowerDensity.FromPicowattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? PicowattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromPicowattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicowattPerCubicInch - - /// - public static PowerDensity PicowattsPerCubicInch(this T value) => PowerDensity.FromPicowattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? PicowattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromPicowattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicowattPerCubicMeter - - /// - public static PowerDensity PicowattsPerCubicMeter(this T value) => PowerDensity.FromPicowattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? PicowattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromPicowattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PicowattPerLiter - - /// - public static PowerDensity PicowattsPerLiter(this T value) => PowerDensity.FromPicowattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? PicowattsPerLiter(this T? value) where T : struct => PowerDensity.FromPicowattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerawattPerCubicFoot - - /// - public static PowerDensity TerawattsPerCubicFoot(this T value) => PowerDensity.FromTerawattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? TerawattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromTerawattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerawattPerCubicInch - - /// - public static PowerDensity TerawattsPerCubicInch(this T value) => PowerDensity.FromTerawattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? TerawattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromTerawattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerawattPerCubicMeter - - /// - public static PowerDensity TerawattsPerCubicMeter(this T value) => PowerDensity.FromTerawattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? TerawattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromTerawattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TerawattPerLiter - - /// - public static PowerDensity TerawattsPerLiter(this T value) => PowerDensity.FromTerawattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? TerawattsPerLiter(this T? value) where T : struct => PowerDensity.FromTerawattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerCubicFoot - - /// - public static PowerDensity WattsPerCubicFoot(this T value) => PowerDensity.FromWattsPerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? WattsPerCubicFoot(this T? value) where T : struct => PowerDensity.FromWattsPerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerCubicInch - - /// - public static PowerDensity WattsPerCubicInch(this T value) => PowerDensity.FromWattsPerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? WattsPerCubicInch(this T? value) where T : struct => PowerDensity.FromWattsPerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerCubicMeter - - /// - public static PowerDensity WattsPerCubicMeter(this T value) => PowerDensity.FromWattsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? WattsPerCubicMeter(this T? value) where T : struct => PowerDensity.FromWattsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerLiter - - /// - public static PowerDensity WattsPerLiter(this T value) => PowerDensity.FromWattsPerLiter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? WattsPerLiter(this T? value) where T : struct => PowerDensity.FromWattsPerLiter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerExtensions.g.cs deleted file mode 100644 index 6b787f7371..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerExtensions.g.cs +++ /dev/null @@ -1,269 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPower -{ - public static class NumberToPowerExtensions - { - #region BoilerHorsepower - - /// - public static Power BoilerHorsepower(this T value) => Power.FromBoilerHorsepower(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? BoilerHorsepower(this T? value) where T : struct => Power.FromBoilerHorsepower(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region BritishThermalUnitPerHour - - /// - public static Power BritishThermalUnitsPerHour(this T value) => Power.FromBritishThermalUnitsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? BritishThermalUnitsPerHour(this T? value) where T : struct => Power.FromBritishThermalUnitsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decawatt - - /// - public static Power Decawatts(this T value) => Power.FromDecawatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Decawatts(this T? value) where T : struct => Power.FromDecawatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Deciwatt - - /// - public static Power Deciwatts(this T value) => Power.FromDeciwatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Deciwatts(this T? value) where T : struct => Power.FromDeciwatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ElectricalHorsepower - - /// - public static Power ElectricalHorsepower(this T value) => Power.FromElectricalHorsepower(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? ElectricalHorsepower(this T? value) where T : struct => Power.FromElectricalHorsepower(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Femtowatt - - /// - public static Power Femtowatts(this T value) => Power.FromFemtowatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Femtowatts(this T? value) where T : struct => Power.FromFemtowatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gigawatt - - /// - public static Power Gigawatts(this T value) => Power.FromGigawatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Gigawatts(this T? value) where T : struct => Power.FromGigawatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HydraulicHorsepower - - /// - public static Power HydraulicHorsepower(this T value) => Power.FromHydraulicHorsepower(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? HydraulicHorsepower(this T? value) where T : struct => Power.FromHydraulicHorsepower(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilobritishThermalUnitPerHour - - /// - public static Power KilobritishThermalUnitsPerHour(this T value) => Power.FromKilobritishThermalUnitsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? KilobritishThermalUnitsPerHour(this T? value) where T : struct => Power.FromKilobritishThermalUnitsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilowatt - - /// - public static Power Kilowatts(this T value) => Power.FromKilowatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Kilowatts(this T? value) where T : struct => Power.FromKilowatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MechanicalHorsepower - - /// - public static Power MechanicalHorsepower(this T value) => Power.FromMechanicalHorsepower(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? MechanicalHorsepower(this T? value) where T : struct => Power.FromMechanicalHorsepower(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megawatt - - /// - public static Power Megawatts(this T value) => Power.FromMegawatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Megawatts(this T? value) where T : struct => Power.FromMegawatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MetricHorsepower - - /// - public static Power MetricHorsepower(this T value) => Power.FromMetricHorsepower(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? MetricHorsepower(this T? value) where T : struct => Power.FromMetricHorsepower(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microwatt - - /// - public static Power Microwatts(this T value) => Power.FromMicrowatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Microwatts(this T? value) where T : struct => Power.FromMicrowatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milliwatt - - /// - public static Power Milliwatts(this T value) => Power.FromMilliwatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Milliwatts(this T? value) where T : struct => Power.FromMilliwatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Nanowatt - - /// - public static Power Nanowatts(this T value) => Power.FromNanowatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Nanowatts(this T? value) where T : struct => Power.FromNanowatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Petawatt - - /// - public static Power Petawatts(this T value) => Power.FromPetawatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Petawatts(this T? value) where T : struct => Power.FromPetawatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Picowatt - - /// - public static Power Picowatts(this T value) => Power.FromPicowatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Picowatts(this T? value) where T : struct => Power.FromPicowatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Terawatt - - /// - public static Power Terawatts(this T value) => Power.FromTerawatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Terawatts(this T? value) where T : struct => Power.FromTerawatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Watt - - /// - public static Power Watts(this T value) => Power.FromWatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? Watts(this T? value) where T : struct => Power.FromWatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerRatioExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerRatioExtensions.g.cs deleted file mode 100644 index df98da38e2..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPowerRatioExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPowerRatio -{ - public static class NumberToPowerRatioExtensions - { - #region DecibelMilliwatt - - /// - public static PowerRatio DecibelMilliwatts(this T value) => PowerRatio.FromDecibelMilliwatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerRatio? DecibelMilliwatts(this T? value) where T : struct => PowerRatio.FromDecibelMilliwatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecibelWatt - - /// - public static PowerRatio DecibelWatts(this T value) => PowerRatio.FromDecibelWatts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerRatio? DecibelWatts(this T? value) where T : struct => PowerRatio.FromDecibelWatts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureChangeRateExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureChangeRateExtensions.g.cs deleted file mode 100644 index afb087b144..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureChangeRateExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPressureChangeRate -{ - public static class NumberToPressureChangeRateExtensions - { - #region AtmospherePerSecond - - /// - public static PressureChangeRate AtmospheresPerSecond(this T value) => PressureChangeRate.FromAtmospheresPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PressureChangeRate? AtmospheresPerSecond(this T? value) where T : struct => PressureChangeRate.FromAtmospheresPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopascalPerSecond - - /// - public static PressureChangeRate KilopascalsPerSecond(this T value) => PressureChangeRate.FromKilopascalsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PressureChangeRate? KilopascalsPerSecond(this T? value) where T : struct => PressureChangeRate.FromKilopascalsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapascalPerSecond - - /// - public static PressureChangeRate MegapascalsPerSecond(this T value) => PressureChangeRate.FromMegapascalsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PressureChangeRate? MegapascalsPerSecond(this T? value) where T : struct => PressureChangeRate.FromMegapascalsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PascalPerSecond - - /// - public static PressureChangeRate PascalsPerSecond(this T value) => PressureChangeRate.FromPascalsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PressureChangeRate? PascalsPerSecond(this T? value) where T : struct => PressureChangeRate.FromPascalsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureExtensions.g.cs deleted file mode 100644 index 8576428515..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToPressureExtensions.g.cs +++ /dev/null @@ -1,512 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToPressure -{ - public static class NumberToPressureExtensions - { - #region Atmosphere - - /// - public static Pressure Atmospheres(this T value) => Pressure.FromAtmospheres(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Atmospheres(this T? value) where T : struct => Pressure.FromAtmospheres(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Bar - - /// - public static Pressure Bars(this T value) => Pressure.FromBars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Bars(this T? value) where T : struct => Pressure.FromBars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Centibar - - /// - public static Pressure Centibars(this T value) => Pressure.FromCentibars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Centibars(this T? value) where T : struct => Pressure.FromCentibars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decapascal - - /// - public static Pressure Decapascals(this T value) => Pressure.FromDecapascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Decapascals(this T? value) where T : struct => Pressure.FromDecapascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Decibar - - /// - public static Pressure Decibars(this T value) => Pressure.FromDecibars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Decibars(this T? value) where T : struct => Pressure.FromDecibars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DynePerSquareCentimeter - - /// - public static Pressure DynesPerSquareCentimeter(this T value) => Pressure.FromDynesPerSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? DynesPerSquareCentimeter(this T? value) where T : struct => Pressure.FromDynesPerSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootOfHead - - /// - public static Pressure FeetOfHead(this T value) => Pressure.FromFeetOfHead(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? FeetOfHead(this T? value) where T : struct => Pressure.FromFeetOfHead(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Gigapascal - - /// - public static Pressure Gigapascals(this T value) => Pressure.FromGigapascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Gigapascals(this T? value) where T : struct => Pressure.FromGigapascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hectopascal - - /// - public static Pressure Hectopascals(this T value) => Pressure.FromHectopascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Hectopascals(this T? value) where T : struct => Pressure.FromHectopascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchOfMercury - - /// - public static Pressure InchesOfMercury(this T value) => Pressure.FromInchesOfMercury(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? InchesOfMercury(this T? value) where T : struct => Pressure.FromInchesOfMercury(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilobar - - /// - public static Pressure Kilobars(this T value) => Pressure.FromKilobars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Kilobars(this T? value) where T : struct => Pressure.FromKilobars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerSquareCentimeter - - /// - public static Pressure KilogramsForcePerSquareCentimeter(this T value) => Pressure.FromKilogramsForcePerSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilogramsForcePerSquareCentimeter(this T? value) where T : struct => Pressure.FromKilogramsForcePerSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerSquareMeter - - /// - public static Pressure KilogramsForcePerSquareMeter(this T value) => Pressure.FromKilogramsForcePerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilogramsForcePerSquareMeter(this T? value) where T : struct => Pressure.FromKilogramsForcePerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerSquareMillimeter - - /// - public static Pressure KilogramsForcePerSquareMillimeter(this T value) => Pressure.FromKilogramsForcePerSquareMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilogramsForcePerSquareMillimeter(this T? value) where T : struct => Pressure.FromKilogramsForcePerSquareMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerSquareCentimeter - - /// - public static Pressure KilonewtonsPerSquareCentimeter(this T value) => Pressure.FromKilonewtonsPerSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilonewtonsPerSquareCentimeter(this T? value) where T : struct => Pressure.FromKilonewtonsPerSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerSquareMeter - - /// - public static Pressure KilonewtonsPerSquareMeter(this T value) => Pressure.FromKilonewtonsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilonewtonsPerSquareMeter(this T? value) where T : struct => Pressure.FromKilonewtonsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerSquareMillimeter - - /// - public static Pressure KilonewtonsPerSquareMillimeter(this T value) => Pressure.FromKilonewtonsPerSquareMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilonewtonsPerSquareMillimeter(this T? value) where T : struct => Pressure.FromKilonewtonsPerSquareMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kilopascal - - /// - public static Pressure Kilopascals(this T value) => Pressure.FromKilopascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Kilopascals(this T? value) where T : struct => Pressure.FromKilopascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForcePerSquareFoot - - /// - public static Pressure KilopoundsForcePerSquareFoot(this T value) => Pressure.FromKilopoundsForcePerSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilopoundsForcePerSquareFoot(this T? value) where T : struct => Pressure.FromKilopoundsForcePerSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForcePerSquareInch - - /// - public static Pressure KilopoundsForcePerSquareInch(this T value) => Pressure.FromKilopoundsForcePerSquareInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? KilopoundsForcePerSquareInch(this T? value) where T : struct => Pressure.FromKilopoundsForcePerSquareInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megabar - - /// - public static Pressure Megabars(this T value) => Pressure.FromMegabars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Megabars(this T? value) where T : struct => Pressure.FromMegabars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonPerSquareMeter - - /// - public static Pressure MeganewtonsPerSquareMeter(this T value) => Pressure.FromMeganewtonsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? MeganewtonsPerSquareMeter(this T? value) where T : struct => Pressure.FromMeganewtonsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Megapascal - - /// - public static Pressure Megapascals(this T value) => Pressure.FromMegapascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Megapascals(this T? value) where T : struct => Pressure.FromMegapascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterOfHead - - /// - public static Pressure MetersOfHead(this T value) => Pressure.FromMetersOfHead(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? MetersOfHead(this T? value) where T : struct => Pressure.FromMetersOfHead(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microbar - - /// - public static Pressure Microbars(this T value) => Pressure.FromMicrobars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Microbars(this T? value) where T : struct => Pressure.FromMicrobars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Micropascal - - /// - public static Pressure Micropascals(this T value) => Pressure.FromMicropascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Micropascals(this T? value) where T : struct => Pressure.FromMicropascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millibar - - /// - public static Pressure Millibars(this T value) => Pressure.FromMillibars(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Millibars(this T? value) where T : struct => Pressure.FromMillibars(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterOfMercury - - /// - public static Pressure MillimetersOfMercury(this T value) => Pressure.FromMillimetersOfMercury(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? MillimetersOfMercury(this T? value) where T : struct => Pressure.FromMillimetersOfMercury(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Millipascal - - /// - public static Pressure Millipascals(this T value) => Pressure.FromMillipascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Millipascals(this T? value) where T : struct => Pressure.FromMillipascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerSquareCentimeter - - /// - public static Pressure NewtonsPerSquareCentimeter(this T value) => Pressure.FromNewtonsPerSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? NewtonsPerSquareCentimeter(this T? value) where T : struct => Pressure.FromNewtonsPerSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerSquareMeter - - /// - public static Pressure NewtonsPerSquareMeter(this T value) => Pressure.FromNewtonsPerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? NewtonsPerSquareMeter(this T? value) where T : struct => Pressure.FromNewtonsPerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerSquareMillimeter - - /// - public static Pressure NewtonsPerSquareMillimeter(this T value) => Pressure.FromNewtonsPerSquareMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? NewtonsPerSquareMillimeter(this T? value) where T : struct => Pressure.FromNewtonsPerSquareMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Pascal - - /// - public static Pressure Pascals(this T value) => Pressure.FromPascals(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Pascals(this T? value) where T : struct => Pressure.FromPascals(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForcePerSquareFoot - - /// - public static Pressure PoundsForcePerSquareFoot(this T value) => Pressure.FromPoundsForcePerSquareFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? PoundsForcePerSquareFoot(this T? value) where T : struct => Pressure.FromPoundsForcePerSquareFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForcePerSquareInch - - /// - public static Pressure PoundsForcePerSquareInch(this T value) => Pressure.FromPoundsForcePerSquareInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? PoundsForcePerSquareInch(this T? value) where T : struct => Pressure.FromPoundsForcePerSquareInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundPerInchSecondSquared - - /// - public static Pressure PoundsPerInchSecondSquared(this T value) => Pressure.FromPoundsPerInchSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? PoundsPerInchSecondSquared(this T? value) where T : struct => Pressure.FromPoundsPerInchSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Psi - - /// - [System.Obsolete("Deprecated due to github issue #215, please use PoundForcePerSquareInch instead")] - public static Pressure Psi(this T value) => Pressure.FromPsi(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Psi(this T? value) where T : struct => Pressure.FromPsi(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TechnicalAtmosphere - - /// - public static Pressure TechnicalAtmospheres(this T value) => Pressure.FromTechnicalAtmospheres(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? TechnicalAtmospheres(this T? value) where T : struct => Pressure.FromTechnicalAtmospheres(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerSquareCentimeter - - /// - public static Pressure TonnesForcePerSquareCentimeter(this T value) => Pressure.FromTonnesForcePerSquareCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? TonnesForcePerSquareCentimeter(this T? value) where T : struct => Pressure.FromTonnesForcePerSquareCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerSquareMeter - - /// - public static Pressure TonnesForcePerSquareMeter(this T value) => Pressure.FromTonnesForcePerSquareMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? TonnesForcePerSquareMeter(this T? value) where T : struct => Pressure.FromTonnesForcePerSquareMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerSquareMillimeter - - /// - public static Pressure TonnesForcePerSquareMillimeter(this T value) => Pressure.FromTonnesForcePerSquareMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? TonnesForcePerSquareMillimeter(this T? value) where T : struct => Pressure.FromTonnesForcePerSquareMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Torr - - /// - public static Pressure Torrs(this T value) => Pressure.FromTorrs(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? Torrs(this T? value) where T : struct => Pressure.FromTorrs(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRatioExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToRatioExtensions.g.cs deleted file mode 100644 index 470f763f82..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRatioExtensions.g.cs +++ /dev/null @@ -1,115 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToRatio -{ - public static class NumberToRatioExtensions - { - #region DecimalFraction - - /// - public static Ratio DecimalFractions(this T value) => Ratio.FromDecimalFractions(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? DecimalFractions(this T? value) where T : struct => Ratio.FromDecimalFractions(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PartPerBillion - - /// - public static Ratio PartsPerBillion(this T value) => Ratio.FromPartsPerBillion(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? PartsPerBillion(this T? value) where T : struct => Ratio.FromPartsPerBillion(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PartPerMillion - - /// - public static Ratio PartsPerMillion(this T value) => Ratio.FromPartsPerMillion(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? PartsPerMillion(this T? value) where T : struct => Ratio.FromPartsPerMillion(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PartPerThousand - - /// - public static Ratio PartsPerThousand(this T value) => Ratio.FromPartsPerThousand(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? PartsPerThousand(this T? value) where T : struct => Ratio.FromPartsPerThousand(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PartPerTrillion - - /// - public static Ratio PartsPerTrillion(this T value) => Ratio.FromPartsPerTrillion(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? PartsPerTrillion(this T? value) where T : struct => Ratio.FromPartsPerTrillion(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Percent - - /// - public static Ratio Percent(this T value) => Ratio.FromPercent(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? Percent(this T? value) where T : struct => Ratio.FromPercent(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactiveEnergyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactiveEnergyExtensions.g.cs deleted file mode 100644 index 9a4594afc3..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactiveEnergyExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToReactiveEnergy -{ - public static class NumberToReactiveEnergyExtensions - { - #region KilovoltampereReactiveHour - - /// - public static ReactiveEnergy KilovoltampereReactiveHours(this T value) => ReactiveEnergy.FromKilovoltampereReactiveHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactiveEnergy? KilovoltampereReactiveHours(this T? value) where T : struct => ReactiveEnergy.FromKilovoltampereReactiveHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegavoltampereReactiveHour - - /// - public static ReactiveEnergy MegavoltampereReactiveHours(this T value) => ReactiveEnergy.FromMegavoltampereReactiveHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactiveEnergy? MegavoltampereReactiveHours(this T? value) where T : struct => ReactiveEnergy.FromMegavoltampereReactiveHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region VoltampereReactiveHour - - /// - public static ReactiveEnergy VoltampereReactiveHours(this T value) => ReactiveEnergy.FromVoltampereReactiveHours(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactiveEnergy? VoltampereReactiveHours(this T? value) where T : struct => ReactiveEnergy.FromVoltampereReactiveHours(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactivePowerExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactivePowerExtensions.g.cs deleted file mode 100644 index 89d6b7f589..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToReactivePowerExtensions.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToReactivePower -{ - public static class NumberToReactivePowerExtensions - { - #region GigavoltampereReactive - - /// - public static ReactivePower GigavoltamperesReactive(this T value) => ReactivePower.FromGigavoltamperesReactive(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactivePower? GigavoltamperesReactive(this T? value) where T : struct => ReactivePower.FromGigavoltamperesReactive(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilovoltampereReactive - - /// - public static ReactivePower KilovoltamperesReactive(this T value) => ReactivePower.FromKilovoltamperesReactive(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactivePower? KilovoltamperesReactive(this T? value) where T : struct => ReactivePower.FromKilovoltamperesReactive(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegavoltampereReactive - - /// - public static ReactivePower MegavoltamperesReactive(this T value) => ReactivePower.FromMegavoltamperesReactive(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactivePower? MegavoltamperesReactive(this T? value) where T : struct => ReactivePower.FromMegavoltamperesReactive(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region VoltampereReactive - - /// - public static ReactivePower VoltamperesReactive(this T value) => ReactivePower.FromVoltamperesReactive(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactivePower? VoltamperesReactive(this T? value) where T : struct => ReactivePower.FromVoltamperesReactive(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalAccelerationExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalAccelerationExtensions.g.cs deleted file mode 100644 index 68b257bddd..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalAccelerationExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToRotationalAcceleration -{ - public static class NumberToRotationalAccelerationExtensions - { - #region DegreePerSecondSquared - - /// - public static RotationalAcceleration DegreesPerSecondSquared(this T value) => RotationalAcceleration.FromDegreesPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalAcceleration? DegreesPerSecondSquared(this T? value) where T : struct => RotationalAcceleration.FromDegreesPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region RadianPerSecondSquared - - /// - public static RotationalAcceleration RadiansPerSecondSquared(this T value) => RotationalAcceleration.FromRadiansPerSecondSquared(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalAcceleration? RadiansPerSecondSquared(this T? value) where T : struct => RotationalAcceleration.FromRadiansPerSecondSquared(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region RevolutionPerMinutePerSecond - - /// - public static RotationalAcceleration RevolutionsPerMinutePerSecond(this T value) => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalAcceleration? RevolutionsPerMinutePerSecond(this T? value) where T : struct => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalSpeedExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalSpeedExtensions.g.cs deleted file mode 100644 index f0512ae33d..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalSpeedExtensions.g.cs +++ /dev/null @@ -1,192 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToRotationalSpeed -{ - public static class NumberToRotationalSpeedExtensions - { - #region CentiradianPerSecond - - /// - public static RotationalSpeed CentiradiansPerSecond(this T value) => RotationalSpeed.FromCentiradiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? CentiradiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromCentiradiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DeciradianPerSecond - - /// - public static RotationalSpeed DeciradiansPerSecond(this T value) => RotationalSpeed.FromDeciradiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? DeciradiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromDeciradiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreePerMinute - - /// - public static RotationalSpeed DegreesPerMinute(this T value) => RotationalSpeed.FromDegreesPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? DegreesPerMinute(this T? value) where T : struct => RotationalSpeed.FromDegreesPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreePerSecond - - /// - public static RotationalSpeed DegreesPerSecond(this T value) => RotationalSpeed.FromDegreesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? DegreesPerSecond(this T? value) where T : struct => RotationalSpeed.FromDegreesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrodegreePerSecond - - /// - public static RotationalSpeed MicrodegreesPerSecond(this T value) => RotationalSpeed.FromMicrodegreesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? MicrodegreesPerSecond(this T? value) where T : struct => RotationalSpeed.FromMicrodegreesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicroradianPerSecond - - /// - public static RotationalSpeed MicroradiansPerSecond(this T value) => RotationalSpeed.FromMicroradiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? MicroradiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromMicroradiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillidegreePerSecond - - /// - public static RotationalSpeed MillidegreesPerSecond(this T value) => RotationalSpeed.FromMillidegreesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? MillidegreesPerSecond(this T? value) where T : struct => RotationalSpeed.FromMillidegreesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilliradianPerSecond - - /// - public static RotationalSpeed MilliradiansPerSecond(this T value) => RotationalSpeed.FromMilliradiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? MilliradiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromMilliradiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanodegreePerSecond - - /// - public static RotationalSpeed NanodegreesPerSecond(this T value) => RotationalSpeed.FromNanodegreesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? NanodegreesPerSecond(this T? value) where T : struct => RotationalSpeed.FromNanodegreesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanoradianPerSecond - - /// - public static RotationalSpeed NanoradiansPerSecond(this T value) => RotationalSpeed.FromNanoradiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? NanoradiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromNanoradiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region RadianPerSecond - - /// - public static RotationalSpeed RadiansPerSecond(this T value) => RotationalSpeed.FromRadiansPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? RadiansPerSecond(this T? value) where T : struct => RotationalSpeed.FromRadiansPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region RevolutionPerMinute - - /// - public static RotationalSpeed RevolutionsPerMinute(this T value) => RotationalSpeed.FromRevolutionsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? RevolutionsPerMinute(this T? value) where T : struct => RotationalSpeed.FromRevolutionsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region RevolutionPerSecond - - /// - public static RotationalSpeed RevolutionsPerSecond(this T value) => RotationalSpeed.FromRevolutionsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? RevolutionsPerSecond(this T? value) where T : struct => RotationalSpeed.FromRevolutionsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessExtensions.g.cs deleted file mode 100644 index 25d863aac9..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToRotationalStiffness -{ - public static class NumberToRotationalStiffnessExtensions - { - #region KilonewtonMeterPerRadian - - /// - public static RotationalStiffness KilonewtonMetersPerRadian(this T value) => RotationalStiffness.FromKilonewtonMetersPerRadian(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffness? KilonewtonMetersPerRadian(this T? value) where T : struct => RotationalStiffness.FromKilonewtonMetersPerRadian(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonMeterPerRadian - - /// - public static RotationalStiffness MeganewtonMetersPerRadian(this T value) => RotationalStiffness.FromMeganewtonMetersPerRadian(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffness? MeganewtonMetersPerRadian(this T? value) where T : struct => RotationalStiffness.FromMeganewtonMetersPerRadian(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonMeterPerRadian - - /// - public static RotationalStiffness NewtonMetersPerRadian(this T value) => RotationalStiffness.FromNewtonMetersPerRadian(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffness? NewtonMetersPerRadian(this T? value) where T : struct => RotationalStiffness.FromNewtonMetersPerRadian(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessPerLengthExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessPerLengthExtensions.g.cs deleted file mode 100644 index d8891117ff..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToRotationalStiffnessPerLengthExtensions.g.cs +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToRotationalStiffnessPerLength -{ - public static class NumberToRotationalStiffnessPerLengthExtensions - { - #region KilonewtonMeterPerRadianPerMeter - - /// - public static RotationalStiffnessPerLength KilonewtonMetersPerRadianPerMeter(this T value) => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffnessPerLength? KilonewtonMetersPerRadianPerMeter(this T? value) where T : struct => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonMeterPerRadianPerMeter - - /// - public static RotationalStiffnessPerLength MeganewtonMetersPerRadianPerMeter(this T value) => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffnessPerLength? MeganewtonMetersPerRadianPerMeter(this T? value) where T : struct => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonMeterPerRadianPerMeter - - /// - public static RotationalStiffnessPerLength NewtonMetersPerRadianPerMeter(this T value) => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffnessPerLength? NewtonMetersPerRadianPerMeter(this T? value) where T : struct => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSolidAngleExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSolidAngleExtensions.g.cs deleted file mode 100644 index b960b70ba1..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSolidAngleExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSolidAngle -{ - public static class NumberToSolidAngleExtensions - { - #region Steradian - - /// - public static SolidAngle Steradians(this T value) => SolidAngle.FromSteradians(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SolidAngle? Steradians(this T? value) where T : struct => SolidAngle.FromSteradians(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEnergyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEnergyExtensions.g.cs deleted file mode 100644 index 873ffd7db8..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEnergyExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSpecificEnergy -{ - public static class NumberToSpecificEnergyExtensions - { - #region CaloriePerGram - - /// - public static SpecificEnergy CaloriesPerGram(this T value) => SpecificEnergy.FromCaloriesPerGram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? CaloriesPerGram(this T? value) where T : struct => SpecificEnergy.FromCaloriesPerGram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region JoulePerKilogram - - /// - public static SpecificEnergy JoulesPerKilogram(this T value) => SpecificEnergy.FromJoulesPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? JoulesPerKilogram(this T? value) where T : struct => SpecificEnergy.FromJoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocaloriePerGram - - /// - public static SpecificEnergy KilocaloriesPerGram(this T value) => SpecificEnergy.FromKilocaloriesPerGram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? KilocaloriesPerGram(this T? value) where T : struct => SpecificEnergy.FromKilocaloriesPerGram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerKilogram - - /// - public static SpecificEnergy KilojoulesPerKilogram(this T value) => SpecificEnergy.FromKilojoulesPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? KilojoulesPerKilogram(this T? value) where T : struct => SpecificEnergy.FromKilojoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilowattHourPerKilogram - - /// - public static SpecificEnergy KilowattHoursPerKilogram(this T value) => SpecificEnergy.FromKilowattHoursPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? KilowattHoursPerKilogram(this T? value) where T : struct => SpecificEnergy.FromKilowattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerKilogram - - /// - public static SpecificEnergy MegajoulesPerKilogram(this T value) => SpecificEnergy.FromMegajoulesPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? MegajoulesPerKilogram(this T? value) where T : struct => SpecificEnergy.FromMegajoulesPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegawattHourPerKilogram - - /// - public static SpecificEnergy MegawattHoursPerKilogram(this T value) => SpecificEnergy.FromMegawattHoursPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? MegawattHoursPerKilogram(this T? value) where T : struct => SpecificEnergy.FromMegawattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattHourPerKilogram - - /// - public static SpecificEnergy WattHoursPerKilogram(this T value) => SpecificEnergy.FromWattHoursPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? WattHoursPerKilogram(this T? value) where T : struct => SpecificEnergy.FromWattHoursPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEntropyExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEntropyExtensions.g.cs deleted file mode 100644 index e9915976d1..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificEntropyExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSpecificEntropy -{ - public static class NumberToSpecificEntropyExtensions - { - #region CaloriePerGramKelvin - - /// - public static SpecificEntropy CaloriesPerGramKelvin(this T value) => SpecificEntropy.FromCaloriesPerGramKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? CaloriesPerGramKelvin(this T? value) where T : struct => SpecificEntropy.FromCaloriesPerGramKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region JoulePerKilogramDegreeCelsius - - /// - public static SpecificEntropy JoulesPerKilogramDegreeCelsius(this T value) => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? JoulesPerKilogramDegreeCelsius(this T? value) where T : struct => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region JoulePerKilogramKelvin - - /// - public static SpecificEntropy JoulesPerKilogramKelvin(this T value) => SpecificEntropy.FromJoulesPerKilogramKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? JoulesPerKilogramKelvin(this T? value) where T : struct => SpecificEntropy.FromJoulesPerKilogramKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocaloriePerGramKelvin - - /// - public static SpecificEntropy KilocaloriesPerGramKelvin(this T value) => SpecificEntropy.FromKilocaloriesPerGramKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? KilocaloriesPerGramKelvin(this T? value) where T : struct => SpecificEntropy.FromKilocaloriesPerGramKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerKilogramDegreeCelsius - - /// - public static SpecificEntropy KilojoulesPerKilogramDegreeCelsius(this T value) => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? KilojoulesPerKilogramDegreeCelsius(this T? value) where T : struct => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilojoulePerKilogramKelvin - - /// - public static SpecificEntropy KilojoulesPerKilogramKelvin(this T value) => SpecificEntropy.FromKilojoulesPerKilogramKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? KilojoulesPerKilogramKelvin(this T? value) where T : struct => SpecificEntropy.FromKilojoulesPerKilogramKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerKilogramDegreeCelsius - - /// - public static SpecificEntropy MegajoulesPerKilogramDegreeCelsius(this T value) => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? MegajoulesPerKilogramDegreeCelsius(this T? value) where T : struct => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegajoulePerKilogramKelvin - - /// - public static SpecificEntropy MegajoulesPerKilogramKelvin(this T value) => SpecificEntropy.FromMegajoulesPerKilogramKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? MegajoulesPerKilogramKelvin(this T? value) where T : struct => SpecificEntropy.FromMegajoulesPerKilogramKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificVolumeExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificVolumeExtensions.g.cs deleted file mode 100644 index 3ac4fad9d2..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificVolumeExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSpecificVolume -{ - public static class NumberToSpecificVolumeExtensions - { - #region CubicFootPerPound - - /// - public static SpecificVolume CubicFeetPerPound(this T value) => SpecificVolume.FromCubicFeetPerPound(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificVolume? CubicFeetPerPound(this T? value) where T : struct => SpecificVolume.FromCubicFeetPerPound(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerKilogram - - /// - public static SpecificVolume CubicMetersPerKilogram(this T value) => SpecificVolume.FromCubicMetersPerKilogram(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificVolume? CubicMetersPerKilogram(this T? value) where T : struct => SpecificVolume.FromCubicMetersPerKilogram(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificWeightExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificWeightExtensions.g.cs deleted file mode 100644 index 96baddecbc..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpecificWeightExtensions.g.cs +++ /dev/null @@ -1,236 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSpecificWeight -{ - public static class NumberToSpecificWeightExtensions - { - #region KilogramForcePerCubicCentimeter - - /// - public static SpecificWeight KilogramsForcePerCubicCentimeter(this T value) => SpecificWeight.FromKilogramsForcePerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilogramsForcePerCubicCentimeter(this T? value) where T : struct => SpecificWeight.FromKilogramsForcePerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerCubicMeter - - /// - public static SpecificWeight KilogramsForcePerCubicMeter(this T value) => SpecificWeight.FromKilogramsForcePerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilogramsForcePerCubicMeter(this T? value) where T : struct => SpecificWeight.FromKilogramsForcePerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForcePerCubicMillimeter - - /// - public static SpecificWeight KilogramsForcePerCubicMillimeter(this T value) => SpecificWeight.FromKilogramsForcePerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilogramsForcePerCubicMillimeter(this T? value) where T : struct => SpecificWeight.FromKilogramsForcePerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerCubicCentimeter - - /// - public static SpecificWeight KilonewtonsPerCubicCentimeter(this T value) => SpecificWeight.FromKilonewtonsPerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilonewtonsPerCubicCentimeter(this T? value) where T : struct => SpecificWeight.FromKilonewtonsPerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerCubicMeter - - /// - public static SpecificWeight KilonewtonsPerCubicMeter(this T value) => SpecificWeight.FromKilonewtonsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilonewtonsPerCubicMeter(this T? value) where T : struct => SpecificWeight.FromKilonewtonsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonPerCubicMillimeter - - /// - public static SpecificWeight KilonewtonsPerCubicMillimeter(this T value) => SpecificWeight.FromKilonewtonsPerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilonewtonsPerCubicMillimeter(this T? value) where T : struct => SpecificWeight.FromKilonewtonsPerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForcePerCubicFoot - - /// - public static SpecificWeight KilopoundsForcePerCubicFoot(this T value) => SpecificWeight.FromKilopoundsForcePerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilopoundsForcePerCubicFoot(this T? value) where T : struct => SpecificWeight.FromKilopoundsForcePerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForcePerCubicInch - - /// - public static SpecificWeight KilopoundsForcePerCubicInch(this T value) => SpecificWeight.FromKilopoundsForcePerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? KilopoundsForcePerCubicInch(this T? value) where T : struct => SpecificWeight.FromKilopoundsForcePerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonPerCubicMeter - - /// - public static SpecificWeight MeganewtonsPerCubicMeter(this T value) => SpecificWeight.FromMeganewtonsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? MeganewtonsPerCubicMeter(this T? value) where T : struct => SpecificWeight.FromMeganewtonsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerCubicCentimeter - - /// - public static SpecificWeight NewtonsPerCubicCentimeter(this T value) => SpecificWeight.FromNewtonsPerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? NewtonsPerCubicCentimeter(this T? value) where T : struct => SpecificWeight.FromNewtonsPerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerCubicMeter - - /// - public static SpecificWeight NewtonsPerCubicMeter(this T value) => SpecificWeight.FromNewtonsPerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? NewtonsPerCubicMeter(this T? value) where T : struct => SpecificWeight.FromNewtonsPerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonPerCubicMillimeter - - /// - public static SpecificWeight NewtonsPerCubicMillimeter(this T value) => SpecificWeight.FromNewtonsPerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? NewtonsPerCubicMillimeter(this T? value) where T : struct => SpecificWeight.FromNewtonsPerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForcePerCubicFoot - - /// - public static SpecificWeight PoundsForcePerCubicFoot(this T value) => SpecificWeight.FromPoundsForcePerCubicFoot(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? PoundsForcePerCubicFoot(this T? value) where T : struct => SpecificWeight.FromPoundsForcePerCubicFoot(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForcePerCubicInch - - /// - public static SpecificWeight PoundsForcePerCubicInch(this T value) => SpecificWeight.FromPoundsForcePerCubicInch(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? PoundsForcePerCubicInch(this T? value) where T : struct => SpecificWeight.FromPoundsForcePerCubicInch(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerCubicCentimeter - - /// - public static SpecificWeight TonnesForcePerCubicCentimeter(this T value) => SpecificWeight.FromTonnesForcePerCubicCentimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? TonnesForcePerCubicCentimeter(this T? value) where T : struct => SpecificWeight.FromTonnesForcePerCubicCentimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerCubicMeter - - /// - public static SpecificWeight TonnesForcePerCubicMeter(this T value) => SpecificWeight.FromTonnesForcePerCubicMeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? TonnesForcePerCubicMeter(this T? value) where T : struct => SpecificWeight.FromTonnesForcePerCubicMeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForcePerCubicMillimeter - - /// - public static SpecificWeight TonnesForcePerCubicMillimeter(this T value) => SpecificWeight.FromTonnesForcePerCubicMillimeter(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? TonnesForcePerCubicMillimeter(this T? value) where T : struct => SpecificWeight.FromTonnesForcePerCubicMillimeter(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpeedExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpeedExtensions.g.cs deleted file mode 100644 index ee9db77b1f..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToSpeedExtensions.g.cs +++ /dev/null @@ -1,401 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToSpeed -{ - public static class NumberToSpeedExtensions - { - #region CentimeterPerHour - - /// - public static Speed CentimetersPerHour(this T value) => Speed.FromCentimetersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? CentimetersPerHour(this T? value) where T : struct => Speed.FromCentimetersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentimeterPerMinute - - /// - public static Speed CentimetersPerMinutes(this T value) => Speed.FromCentimetersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? CentimetersPerMinutes(this T? value) where T : struct => Speed.FromCentimetersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CentimeterPerSecond - - /// - public static Speed CentimetersPerSecond(this T value) => Speed.FromCentimetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? CentimetersPerSecond(this T? value) where T : struct => Speed.FromCentimetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecimeterPerMinute - - /// - public static Speed DecimetersPerMinutes(this T value) => Speed.FromDecimetersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? DecimetersPerMinutes(this T? value) where T : struct => Speed.FromDecimetersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecimeterPerSecond - - /// - public static Speed DecimetersPerSecond(this T value) => Speed.FromDecimetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? DecimetersPerSecond(this T? value) where T : struct => Speed.FromDecimetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootPerHour - - /// - public static Speed FeetPerHour(this T value) => Speed.FromFeetPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? FeetPerHour(this T? value) where T : struct => Speed.FromFeetPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootPerMinute - - /// - public static Speed FeetPerMinute(this T value) => Speed.FromFeetPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? FeetPerMinute(this T? value) where T : struct => Speed.FromFeetPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region FootPerSecond - - /// - public static Speed FeetPerSecond(this T value) => Speed.FromFeetPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? FeetPerSecond(this T? value) where T : struct => Speed.FromFeetPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchPerHour - - /// - public static Speed InchesPerHour(this T value) => Speed.FromInchesPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? InchesPerHour(this T? value) where T : struct => Speed.FromInchesPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchPerMinute - - /// - public static Speed InchesPerMinute(this T value) => Speed.FromInchesPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? InchesPerMinute(this T? value) where T : struct => Speed.FromInchesPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region InchPerSecond - - /// - public static Speed InchesPerSecond(this T value) => Speed.FromInchesPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? InchesPerSecond(this T? value) where T : struct => Speed.FromInchesPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilometerPerHour - - /// - public static Speed KilometersPerHour(this T value) => Speed.FromKilometersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? KilometersPerHour(this T? value) where T : struct => Speed.FromKilometersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilometerPerMinute - - /// - public static Speed KilometersPerMinutes(this T value) => Speed.FromKilometersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? KilometersPerMinutes(this T? value) where T : struct => Speed.FromKilometersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilometerPerSecond - - /// - public static Speed KilometersPerSecond(this T value) => Speed.FromKilometersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? KilometersPerSecond(this T? value) where T : struct => Speed.FromKilometersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Knot - - /// - public static Speed Knots(this T value) => Speed.FromKnots(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? Knots(this T? value) where T : struct => Speed.FromKnots(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterPerHour - - /// - public static Speed MetersPerHour(this T value) => Speed.FromMetersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MetersPerHour(this T? value) where T : struct => Speed.FromMetersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterPerMinute - - /// - public static Speed MetersPerMinutes(this T value) => Speed.FromMetersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MetersPerMinutes(this T? value) where T : struct => Speed.FromMetersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeterPerSecond - - /// - public static Speed MetersPerSecond(this T value) => Speed.FromMetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MetersPerSecond(this T? value) where T : struct => Speed.FromMetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrometerPerMinute - - /// - public static Speed MicrometersPerMinutes(this T value) => Speed.FromMicrometersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MicrometersPerMinutes(this T? value) where T : struct => Speed.FromMicrometersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrometerPerSecond - - /// - public static Speed MicrometersPerSecond(this T value) => Speed.FromMicrometersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MicrometersPerSecond(this T? value) where T : struct => Speed.FromMicrometersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MilePerHour - - /// - public static Speed MilesPerHour(this T value) => Speed.FromMilesPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MilesPerHour(this T? value) where T : struct => Speed.FromMilesPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterPerHour - - /// - public static Speed MillimetersPerHour(this T value) => Speed.FromMillimetersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MillimetersPerHour(this T? value) where T : struct => Speed.FromMillimetersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterPerMinute - - /// - public static Speed MillimetersPerMinutes(this T value) => Speed.FromMillimetersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MillimetersPerMinutes(this T? value) where T : struct => Speed.FromMillimetersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillimeterPerSecond - - /// - public static Speed MillimetersPerSecond(this T value) => Speed.FromMillimetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? MillimetersPerSecond(this T? value) where T : struct => Speed.FromMillimetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanometerPerMinute - - /// - public static Speed NanometersPerMinutes(this T value) => Speed.FromNanometersPerMinutes(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? NanometersPerMinutes(this T? value) where T : struct => Speed.FromNanometersPerMinutes(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanometerPerSecond - - /// - public static Speed NanometersPerSecond(this T value) => Speed.FromNanometersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? NanometersPerSecond(this T? value) where T : struct => Speed.FromNanometersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsSurveyFootPerHour - - /// - public static Speed UsSurveyFeetPerHour(this T value) => Speed.FromUsSurveyFeetPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? UsSurveyFeetPerHour(this T? value) where T : struct => Speed.FromUsSurveyFeetPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsSurveyFootPerMinute - - /// - public static Speed UsSurveyFeetPerMinute(this T value) => Speed.FromUsSurveyFeetPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? UsSurveyFeetPerMinute(this T? value) where T : struct => Speed.FromUsSurveyFeetPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsSurveyFootPerSecond - - /// - public static Speed UsSurveyFeetPerSecond(this T value) => Speed.FromUsSurveyFeetPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? UsSurveyFeetPerSecond(this T? value) where T : struct => Speed.FromUsSurveyFeetPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region YardPerHour - - /// - public static Speed YardsPerHour(this T value) => Speed.FromYardsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? YardsPerHour(this T? value) where T : struct => Speed.FromYardsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region YardPerMinute - - /// - public static Speed YardsPerMinute(this T value) => Speed.FromYardsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? YardsPerMinute(this T? value) where T : struct => Speed.FromYardsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region YardPerSecond - - /// - public static Speed YardsPerSecond(this T value) => Speed.FromYardsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? YardsPerSecond(this T? value) where T : struct => Speed.FromYardsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureChangeRateExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureChangeRateExtensions.g.cs deleted file mode 100644 index 3e6946be23..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureChangeRateExtensions.g.cs +++ /dev/null @@ -1,159 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToTemperatureChangeRate -{ - public static class NumberToTemperatureChangeRateExtensions - { - #region CentidegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate CentidegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? CentidegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecadegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate DecadegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? DecadegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecidegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate DecidegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? DecidegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeCelsiusPerMinute - - /// - public static TemperatureChangeRate DegreesCelsiusPerMinute(this T value) => TemperatureChangeRate.FromDegreesCelsiusPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? DegreesCelsiusPerMinute(this T? value) where T : struct => TemperatureChangeRate.FromDegreesCelsiusPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate DegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromDegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? DegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromDegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HectodegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate HectodegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? HectodegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilodegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate KilodegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? KilodegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrodegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate MicrodegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? MicrodegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillidegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate MillidegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? MillidegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanodegreeCelsiusPerSecond - - /// - public static TemperatureChangeRate NanodegreesCelsiusPerSecond(this T value) => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? NanodegreesCelsiusPerSecond(this T? value) where T : struct => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureDeltaExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureDeltaExtensions.g.cs deleted file mode 100644 index 1b2559ee15..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureDeltaExtensions.g.cs +++ /dev/null @@ -1,233 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToTemperatureDelta -{ - public static class NumberToTemperatureDeltaExtensions - { - #region DegreeCelsius - - /// - public static TemperatureDelta DegreesCelsius(this T value) => TemperatureDelta.FromDegreesCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesCelsius(this T? value) where T : struct => TemperatureDelta.FromDegreesCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeCelsiusDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeCelsius instead")] - public static TemperatureDelta DegreesCelsiusDelta(this T value) => TemperatureDelta.FromDegreesCelsiusDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesCelsiusDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesCelsiusDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeDelisle - - /// - public static TemperatureDelta DegreesDelisle(this T value) => TemperatureDelta.FromDegreesDelisle(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesDelisle(this T? value) where T : struct => TemperatureDelta.FromDegreesDelisle(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeDelisleDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeDelisle instead")] - public static TemperatureDelta DegreesDelisleDelta(this T value) => TemperatureDelta.FromDegreesDelisleDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesDelisleDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesDelisleDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeFahrenheit - - /// - public static TemperatureDelta DegreesFahrenheit(this T value) => TemperatureDelta.FromDegreesFahrenheit(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesFahrenheit(this T? value) where T : struct => TemperatureDelta.FromDegreesFahrenheit(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeFahrenheitDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeFahrenheit instead")] - public static TemperatureDelta DegreesFahrenheitDelta(this T value) => TemperatureDelta.FromDegreesFahrenheitDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesFahrenheitDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesFahrenheitDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeNewton - - /// - public static TemperatureDelta DegreesNewton(this T value) => TemperatureDelta.FromDegreesNewton(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesNewton(this T? value) where T : struct => TemperatureDelta.FromDegreesNewton(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeNewtonDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeNewton instead")] - public static TemperatureDelta DegreesNewtonDelta(this T value) => TemperatureDelta.FromDegreesNewtonDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesNewtonDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesNewtonDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRankine - - /// - public static TemperatureDelta DegreesRankine(this T value) => TemperatureDelta.FromDegreesRankine(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesRankine(this T? value) where T : struct => TemperatureDelta.FromDegreesRankine(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRankineDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRankine instead")] - public static TemperatureDelta DegreesRankineDelta(this T value) => TemperatureDelta.FromDegreesRankineDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesRankineDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesRankineDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeReaumur - - /// - public static TemperatureDelta DegreesReaumur(this T value) => TemperatureDelta.FromDegreesReaumur(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesReaumur(this T? value) where T : struct => TemperatureDelta.FromDegreesReaumur(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeReaumurDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeReaumur instead")] - public static TemperatureDelta DegreesReaumurDelta(this T value) => TemperatureDelta.FromDegreesReaumurDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesReaumurDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesReaumurDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRoemer - - /// - public static TemperatureDelta DegreesRoemer(this T value) => TemperatureDelta.FromDegreesRoemer(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesRoemer(this T? value) where T : struct => TemperatureDelta.FromDegreesRoemer(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRoemerDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRoemer instead")] - public static TemperatureDelta DegreesRoemerDelta(this T value) => TemperatureDelta.FromDegreesRoemerDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? DegreesRoemerDelta(this T? value) where T : struct => TemperatureDelta.FromDegreesRoemerDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kelvin - - /// - public static TemperatureDelta Kelvins(this T value) => TemperatureDelta.FromKelvins(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? Kelvins(this T? value) where T : struct => TemperatureDelta.FromKelvins(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KelvinDelta - - /// - [System.Obsolete("Deprecated due to github issue #180, please use Kelvin instead")] - public static TemperatureDelta KelvinsDelta(this T value) => TemperatureDelta.FromKelvinsDelta(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? KelvinsDelta(this T? value) where T : struct => TemperatureDelta.FromKelvinsDelta(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureExtensions.g.cs deleted file mode 100644 index 74b3d22047..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTemperatureExtensions.g.cs +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToTemperature -{ - public static class NumberToTemperatureExtensions - { - #region DegreeCelsius - - /// - public static Temperature DegreesCelsius(this T value) => Temperature.FromDegreesCelsius(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesCelsius(this T? value) where T : struct => Temperature.FromDegreesCelsius(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeDelisle - - /// - public static Temperature DegreesDelisle(this T value) => Temperature.FromDegreesDelisle(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesDelisle(this T? value) where T : struct => Temperature.FromDegreesDelisle(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeFahrenheit - - /// - public static Temperature DegreesFahrenheit(this T value) => Temperature.FromDegreesFahrenheit(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesFahrenheit(this T? value) where T : struct => Temperature.FromDegreesFahrenheit(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeNewton - - /// - public static Temperature DegreesNewton(this T value) => Temperature.FromDegreesNewton(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesNewton(this T? value) where T : struct => Temperature.FromDegreesNewton(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRankine - - /// - public static Temperature DegreesRankine(this T value) => Temperature.FromDegreesRankine(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesRankine(this T? value) where T : struct => Temperature.FromDegreesRankine(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeReaumur - - /// - public static Temperature DegreesReaumur(this T value) => Temperature.FromDegreesReaumur(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesReaumur(this T? value) where T : struct => Temperature.FromDegreesReaumur(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DegreeRoemer - - /// - public static Temperature DegreesRoemer(this T value) => Temperature.FromDegreesRoemer(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? DegreesRoemer(this T? value) where T : struct => Temperature.FromDegreesRoemer(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kelvin - - /// - public static Temperature Kelvins(this T value) => Temperature.FromKelvins(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? Kelvins(this T? value) where T : struct => Temperature.FromKelvins(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalConductivityExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalConductivityExtensions.g.cs deleted file mode 100644 index dc9c3d7539..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalConductivityExtensions.g.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToThermalConductivity -{ - public static class NumberToThermalConductivityExtensions - { - #region BtuPerHourFootFahrenheit - - /// - public static ThermalConductivity BtusPerHourFootFahrenheit(this T value) => ThermalConductivity.FromBtusPerHourFootFahrenheit(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalConductivity? BtusPerHourFootFahrenheit(this T? value) where T : struct => ThermalConductivity.FromBtusPerHourFootFahrenheit(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region WattPerMeterKelvin - - /// - public static ThermalConductivity WattsPerMeterKelvin(this T value) => ThermalConductivity.FromWattsPerMeterKelvin(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalConductivity? WattsPerMeterKelvin(this T? value) where T : struct => ThermalConductivity.FromWattsPerMeterKelvin(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalResistanceExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalResistanceExtensions.g.cs deleted file mode 100644 index cd13575d0a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToThermalResistanceExtensions.g.cs +++ /dev/null @@ -1,104 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToThermalResistance -{ - public static class NumberToThermalResistanceExtensions - { - #region HourSquareFeetDegreeFahrenheitPerBtu - - /// - public static ThermalResistance HourSquareFeetDegreesFahrenheitPerBtu(this T value) => ThermalResistance.FromHourSquareFeetDegreesFahrenheitPerBtu(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? HourSquareFeetDegreesFahrenheitPerBtu(this T? value) where T : struct => ThermalResistance.FromHourSquareFeetDegreesFahrenheitPerBtu(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareCentimeterHourDegreeCelsiusPerKilocalorie - - /// - public static ThermalResistance SquareCentimeterHourDegreesCelsiusPerKilocalorie(this T value) => ThermalResistance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? SquareCentimeterHourDegreesCelsiusPerKilocalorie(this T? value) where T : struct => ThermalResistance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareCentimeterKelvinPerWatt - - /// - public static ThermalResistance SquareCentimeterKelvinsPerWatt(this T value) => ThermalResistance.FromSquareCentimeterKelvinsPerWatt(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? SquareCentimeterKelvinsPerWatt(this T? value) where T : struct => ThermalResistance.FromSquareCentimeterKelvinsPerWatt(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMeterDegreeCelsiusPerWatt - - /// - public static ThermalResistance SquareMeterDegreesCelsiusPerWatt(this T value) => ThermalResistance.FromSquareMeterDegreesCelsiusPerWatt(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? SquareMeterDegreesCelsiusPerWatt(this T? value) where T : struct => ThermalResistance.FromSquareMeterDegreesCelsiusPerWatt(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region SquareMeterKelvinPerKilowatt - - /// - public static ThermalResistance SquareMeterKelvinsPerKilowatt(this T value) => ThermalResistance.FromSquareMeterKelvinsPerKilowatt(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? SquareMeterKelvinsPerKilowatt(this T? value) where T : struct => ThermalResistance.FromSquareMeterKelvinsPerKilowatt(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTorqueExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToTorqueExtensions.g.cs deleted file mode 100644 index 3e373c103a..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToTorqueExtensions.g.cs +++ /dev/null @@ -1,280 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToTorque -{ - public static class NumberToTorqueExtensions - { - #region KilogramForceCentimeter - - /// - public static Torque KilogramForceCentimeters(this T value) => Torque.FromKilogramForceCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilogramForceCentimeters(this T? value) where T : struct => Torque.FromKilogramForceCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForceMeter - - /// - public static Torque KilogramForceMeters(this T value) => Torque.FromKilogramForceMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilogramForceMeters(this T? value) where T : struct => Torque.FromKilogramForceMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilogramForceMillimeter - - /// - public static Torque KilogramForceMillimeters(this T value) => Torque.FromKilogramForceMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilogramForceMillimeters(this T? value) where T : struct => Torque.FromKilogramForceMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonCentimeter - - /// - public static Torque KilonewtonCentimeters(this T value) => Torque.FromKilonewtonCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilonewtonCentimeters(this T? value) where T : struct => Torque.FromKilonewtonCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonMeter - - /// - public static Torque KilonewtonMeters(this T value) => Torque.FromKilonewtonMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilonewtonMeters(this T? value) where T : struct => Torque.FromKilonewtonMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilonewtonMillimeter - - /// - public static Torque KilonewtonMillimeters(this T value) => Torque.FromKilonewtonMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilonewtonMillimeters(this T? value) where T : struct => Torque.FromKilonewtonMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForceFoot - - /// - public static Torque KilopoundForceFeet(this T value) => Torque.FromKilopoundForceFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilopoundForceFeet(this T? value) where T : struct => Torque.FromKilopoundForceFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilopoundForceInch - - /// - public static Torque KilopoundForceInches(this T value) => Torque.FromKilopoundForceInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? KilopoundForceInches(this T? value) where T : struct => Torque.FromKilopoundForceInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonCentimeter - - /// - public static Torque MeganewtonCentimeters(this T value) => Torque.FromMeganewtonCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? MeganewtonCentimeters(this T? value) where T : struct => Torque.FromMeganewtonCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonMeter - - /// - public static Torque MeganewtonMeters(this T value) => Torque.FromMeganewtonMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? MeganewtonMeters(this T? value) where T : struct => Torque.FromMeganewtonMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MeganewtonMillimeter - - /// - public static Torque MeganewtonMillimeters(this T value) => Torque.FromMeganewtonMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? MeganewtonMillimeters(this T? value) where T : struct => Torque.FromMeganewtonMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapoundForceFoot - - /// - public static Torque MegapoundForceFeet(this T value) => Torque.FromMegapoundForceFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? MegapoundForceFeet(this T? value) where T : struct => Torque.FromMegapoundForceFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegapoundForceInch - - /// - public static Torque MegapoundForceInches(this T value) => Torque.FromMegapoundForceInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? MegapoundForceInches(this T? value) where T : struct => Torque.FromMegapoundForceInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonCentimeter - - /// - public static Torque NewtonCentimeters(this T value) => Torque.FromNewtonCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? NewtonCentimeters(this T? value) where T : struct => Torque.FromNewtonCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonMeter - - /// - public static Torque NewtonMeters(this T value) => Torque.FromNewtonMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? NewtonMeters(this T? value) where T : struct => Torque.FromNewtonMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NewtonMillimeter - - /// - public static Torque NewtonMillimeters(this T value) => Torque.FromNewtonMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? NewtonMillimeters(this T? value) where T : struct => Torque.FromNewtonMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForceFoot - - /// - public static Torque PoundForceFeet(this T value) => Torque.FromPoundForceFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? PoundForceFeet(this T? value) where T : struct => Torque.FromPoundForceFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region PoundForceInch - - /// - public static Torque PoundForceInches(this T value) => Torque.FromPoundForceInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? PoundForceInches(this T? value) where T : struct => Torque.FromPoundForceInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForceCentimeter - - /// - public static Torque TonneForceCentimeters(this T value) => Torque.FromTonneForceCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? TonneForceCentimeters(this T? value) where T : struct => Torque.FromTonneForceCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForceMeter - - /// - public static Torque TonneForceMeters(this T value) => Torque.FromTonneForceMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? TonneForceMeters(this T? value) where T : struct => Torque.FromTonneForceMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region TonneForceMillimeter - - /// - public static Torque TonneForceMillimeters(this T value) => Torque.FromTonneForceMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? TonneForceMillimeters(this T? value) where T : struct => Torque.FromTonneForceMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVitaminAExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToVitaminAExtensions.g.cs deleted file mode 100644 index 748f471f95..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVitaminAExtensions.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 Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToVitaminA -{ - public static class NumberToVitaminAExtensions - { - #region InternationalUnit - - /// - public static VitaminA InternationalUnits(this T value) => VitaminA.FromInternationalUnits(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VitaminA? InternationalUnits(this T? value) where T : struct => VitaminA.FromInternationalUnits(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeExtensions.g.cs deleted file mode 100644 index d470d7c685..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeExtensions.g.cs +++ /dev/null @@ -1,546 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToVolume -{ - public static class NumberToVolumeExtensions - { - #region AuTablespoon - - /// - public static Volume AuTablespoons(this T value) => Volume.FromAuTablespoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? AuTablespoons(this T? value) where T : struct => Volume.FromAuTablespoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Centiliter - - /// - public static Volume Centiliters(this T value) => Volume.FromCentiliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Centiliters(this T? value) where T : struct => Volume.FromCentiliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicCentimeter - - /// - public static Volume CubicCentimeters(this T value) => Volume.FromCubicCentimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicCentimeters(this T? value) where T : struct => Volume.FromCubicCentimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicDecimeter - - /// - public static Volume CubicDecimeters(this T value) => Volume.FromCubicDecimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicDecimeters(this T? value) where T : struct => Volume.FromCubicDecimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFoot - - /// - public static Volume CubicFeet(this T value) => Volume.FromCubicFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicFeet(this T? value) where T : struct => Volume.FromCubicFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicInch - - /// - public static Volume CubicInches(this T value) => Volume.FromCubicInches(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicInches(this T? value) where T : struct => Volume.FromCubicInches(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicKilometer - - /// - public static Volume CubicKilometers(this T value) => Volume.FromCubicKilometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicKilometers(this T? value) where T : struct => Volume.FromCubicKilometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeter - - /// - public static Volume CubicMeters(this T value) => Volume.FromCubicMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicMeters(this T? value) where T : struct => Volume.FromCubicMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMicrometer - - /// - public static Volume CubicMicrometers(this T value) => Volume.FromCubicMicrometers(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicMicrometers(this T? value) where T : struct => Volume.FromCubicMicrometers(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMile - - /// - public static Volume CubicMiles(this T value) => Volume.FromCubicMiles(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicMiles(this T? value) where T : struct => Volume.FromCubicMiles(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMillimeter - - /// - public static Volume CubicMillimeters(this T value) => Volume.FromCubicMillimeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicMillimeters(this T? value) where T : struct => Volume.FromCubicMillimeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYard - - /// - public static Volume CubicYards(this T value) => Volume.FromCubicYards(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? CubicYards(this T? value) where T : struct => Volume.FromCubicYards(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Deciliter - - /// - public static Volume Deciliters(this T value) => Volume.FromDeciliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Deciliters(this T? value) where T : struct => Volume.FromDeciliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HectocubicFoot - - /// - public static Volume HectocubicFeet(this T value) => Volume.FromHectocubicFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? HectocubicFeet(this T? value) where T : struct => Volume.FromHectocubicFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region HectocubicMeter - - /// - public static Volume HectocubicMeters(this T value) => Volume.FromHectocubicMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? HectocubicMeters(this T? value) where T : struct => Volume.FromHectocubicMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Hectoliter - - /// - public static Volume Hectoliters(this T value) => Volume.FromHectoliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Hectoliters(this T? value) where T : struct => Volume.FromHectoliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ImperialBeerBarrel - - /// - public static Volume ImperialBeerBarrels(this T value) => Volume.FromImperialBeerBarrels(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? ImperialBeerBarrels(this T? value) where T : struct => Volume.FromImperialBeerBarrels(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ImperialGallon - - /// - public static Volume ImperialGallons(this T value) => Volume.FromImperialGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? ImperialGallons(this T? value) where T : struct => Volume.FromImperialGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region ImperialOunce - - /// - public static Volume ImperialOunces(this T value) => Volume.FromImperialOunces(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? ImperialOunces(this T? value) where T : struct => Volume.FromImperialOunces(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocubicFoot - - /// - public static Volume KilocubicFeet(this T value) => Volume.FromKilocubicFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? KilocubicFeet(this T? value) where T : struct => Volume.FromKilocubicFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilocubicMeter - - /// - public static Volume KilocubicMeters(this T value) => Volume.FromKilocubicMeters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? KilocubicMeters(this T? value) where T : struct => Volume.FromKilocubicMeters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KiloimperialGallon - - /// - public static Volume KiloimperialGallons(this T value) => Volume.FromKiloimperialGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? KiloimperialGallons(this T? value) where T : struct => Volume.FromKiloimperialGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Kiloliter - - /// - public static Volume Kiloliters(this T value) => Volume.FromKiloliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Kiloliters(this T? value) where T : struct => Volume.FromKiloliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilousGallon - - /// - public static Volume KilousGallons(this T value) => Volume.FromKilousGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? KilousGallons(this T? value) where T : struct => Volume.FromKilousGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Liter - - /// - public static Volume Liters(this T value) => Volume.FromLiters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Liters(this T? value) where T : struct => Volume.FromLiters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegacubicFoot - - /// - public static Volume MegacubicFeet(this T value) => Volume.FromMegacubicFeet(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? MegacubicFeet(this T? value) where T : struct => Volume.FromMegacubicFeet(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegaimperialGallon - - /// - public static Volume MegaimperialGallons(this T value) => Volume.FromMegaimperialGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? MegaimperialGallons(this T? value) where T : struct => Volume.FromMegaimperialGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MegausGallon - - /// - public static Volume MegausGallons(this T value) => Volume.FromMegausGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? MegausGallons(this T? value) where T : struct => Volume.FromMegausGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MetricCup - - /// - public static Volume MetricCups(this T value) => Volume.FromMetricCups(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? MetricCups(this T? value) where T : struct => Volume.FromMetricCups(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MetricTeaspoon - - /// - public static Volume MetricTeaspoons(this T value) => Volume.FromMetricTeaspoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? MetricTeaspoons(this T? value) where T : struct => Volume.FromMetricTeaspoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Microliter - - /// - public static Volume Microliters(this T value) => Volume.FromMicroliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Microliters(this T? value) where T : struct => Volume.FromMicroliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Milliliter - - /// - public static Volume Milliliters(this T value) => Volume.FromMilliliters(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Milliliters(this T? value) where T : struct => Volume.FromMilliliters(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OilBarrel - - /// - public static Volume OilBarrels(this T value) => Volume.FromOilBarrels(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? OilBarrels(this T? value) where T : struct => Volume.FromOilBarrels(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Tablespoon - - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTablespoon instead")] - public static Volume Tablespoons(this T value) => Volume.FromTablespoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Tablespoons(this T? value) where T : struct => Volume.FromTablespoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region Teaspoon - - /// - [System.Obsolete("Deprecated due to github issue #134, please use UsTeaspoon instead")] - public static Volume Teaspoons(this T value) => Volume.FromTeaspoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? Teaspoons(this T? value) where T : struct => Volume.FromTeaspoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UkTablespoon - - /// - public static Volume UkTablespoons(this T value) => Volume.FromUkTablespoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UkTablespoons(this T? value) where T : struct => Volume.FromUkTablespoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsBeerBarrel - - /// - public static Volume UsBeerBarrels(this T value) => Volume.FromUsBeerBarrels(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsBeerBarrels(this T? value) where T : struct => Volume.FromUsBeerBarrels(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsCustomaryCup - - /// - public static Volume UsCustomaryCups(this T value) => Volume.FromUsCustomaryCups(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsCustomaryCups(this T? value) where T : struct => Volume.FromUsCustomaryCups(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallon - - /// - public static Volume UsGallons(this T value) => Volume.FromUsGallons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsGallons(this T? value) where T : struct => Volume.FromUsGallons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsLegalCup - - /// - public static Volume UsLegalCups(this T value) => Volume.FromUsLegalCups(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsLegalCups(this T? value) where T : struct => Volume.FromUsLegalCups(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsOunce - - /// - public static Volume UsOunces(this T value) => Volume.FromUsOunces(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsOunces(this T? value) where T : struct => Volume.FromUsOunces(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsPint - - /// - public static Volume UsPints(this T value) => Volume.FromUsPints(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsPints(this T? value) where T : struct => Volume.FromUsPints(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsQuart - - /// - public static Volume UsQuarts(this T value) => Volume.FromUsQuarts(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsQuarts(this T? value) where T : struct => Volume.FromUsQuarts(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsTablespoon - - /// - public static Volume UsTablespoons(this T value) => Volume.FromUsTablespoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsTablespoons(this T? value) where T : struct => Volume.FromUsTablespoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsTeaspoon - - /// - public static Volume UsTeaspoons(this T value) => Volume.FromUsTeaspoons(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? UsTeaspoons(this T? value) where T : struct => Volume.FromUsTeaspoons(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeFlowExtensions.g.cs b/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeFlowExtensions.g.cs deleted file mode 100644 index 57ae3aefb5..0000000000 --- a/UnitsNet/GeneratedCode/Extensions/Number/NumberToVolumeFlowExtensions.g.cs +++ /dev/null @@ -1,357 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberToVolumeFlow -{ - public static class NumberToVolumeFlowExtensions - { - #region CentilitersPerMinute - - /// - public static VolumeFlow CentilitersPerMinute(this T value) => VolumeFlow.FromCentilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CentilitersPerMinute(this T? value) where T : struct => VolumeFlow.FromCentilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicDecimeterPerMinute - - /// - public static VolumeFlow CubicDecimetersPerMinute(this T value) => VolumeFlow.FromCubicDecimetersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicDecimetersPerMinute(this T? value) where T : struct => VolumeFlow.FromCubicDecimetersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerHour - - /// - public static VolumeFlow CubicFeetPerHour(this T value) => VolumeFlow.FromCubicFeetPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicFeetPerHour(this T? value) where T : struct => VolumeFlow.FromCubicFeetPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerMinute - - /// - public static VolumeFlow CubicFeetPerMinute(this T value) => VolumeFlow.FromCubicFeetPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicFeetPerMinute(this T? value) where T : struct => VolumeFlow.FromCubicFeetPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicFootPerSecond - - /// - public static VolumeFlow CubicFeetPerSecond(this T value) => VolumeFlow.FromCubicFeetPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicFeetPerSecond(this T? value) where T : struct => VolumeFlow.FromCubicFeetPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerHour - - /// - public static VolumeFlow CubicMetersPerHour(this T value) => VolumeFlow.FromCubicMetersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicMetersPerHour(this T? value) where T : struct => VolumeFlow.FromCubicMetersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerMinute - - /// - public static VolumeFlow CubicMetersPerMinute(this T value) => VolumeFlow.FromCubicMetersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicMetersPerMinute(this T? value) where T : struct => VolumeFlow.FromCubicMetersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMeterPerSecond - - /// - public static VolumeFlow CubicMetersPerSecond(this T value) => VolumeFlow.FromCubicMetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicMetersPerSecond(this T? value) where T : struct => VolumeFlow.FromCubicMetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicMillimeterPerSecond - - /// - public static VolumeFlow CubicMillimetersPerSecond(this T value) => VolumeFlow.FromCubicMillimetersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicMillimetersPerSecond(this T? value) where T : struct => VolumeFlow.FromCubicMillimetersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerHour - - /// - public static VolumeFlow CubicYardsPerHour(this T value) => VolumeFlow.FromCubicYardsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicYardsPerHour(this T? value) where T : struct => VolumeFlow.FromCubicYardsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerMinute - - /// - public static VolumeFlow CubicYardsPerMinute(this T value) => VolumeFlow.FromCubicYardsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicYardsPerMinute(this T? value) where T : struct => VolumeFlow.FromCubicYardsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region CubicYardPerSecond - - /// - public static VolumeFlow CubicYardsPerSecond(this T value) => VolumeFlow.FromCubicYardsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? CubicYardsPerSecond(this T? value) where T : struct => VolumeFlow.FromCubicYardsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region DecilitersPerMinute - - /// - public static VolumeFlow DecilitersPerMinute(this T value) => VolumeFlow.FromDecilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? DecilitersPerMinute(this T? value) where T : struct => VolumeFlow.FromDecilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilolitersPerMinute - - /// - public static VolumeFlow KilolitersPerMinute(this T value) => VolumeFlow.FromKilolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? KilolitersPerMinute(this T? value) where T : struct => VolumeFlow.FromKilolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region KilousGallonsPerMinute - - /// - public static VolumeFlow KilousGallonsPerMinute(this T value) => VolumeFlow.FromKilousGallonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? KilousGallonsPerMinute(this T? value) where T : struct => VolumeFlow.FromKilousGallonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerHour - - /// - public static VolumeFlow LitersPerHour(this T value) => VolumeFlow.FromLitersPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? LitersPerHour(this T? value) where T : struct => VolumeFlow.FromLitersPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerMinute - - /// - public static VolumeFlow LitersPerMinute(this T value) => VolumeFlow.FromLitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? LitersPerMinute(this T? value) where T : struct => VolumeFlow.FromLitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region LitersPerSecond - - /// - public static VolumeFlow LitersPerSecond(this T value) => VolumeFlow.FromLitersPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? LitersPerSecond(this T? value) where T : struct => VolumeFlow.FromLitersPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MicrolitersPerMinute - - /// - public static VolumeFlow MicrolitersPerMinute(this T value) => VolumeFlow.FromMicrolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? MicrolitersPerMinute(this T? value) where T : struct => VolumeFlow.FromMicrolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillilitersPerMinute - - /// - public static VolumeFlow MillilitersPerMinute(this T value) => VolumeFlow.FromMillilitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? MillilitersPerMinute(this T? value) where T : struct => VolumeFlow.FromMillilitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region MillionUsGallonsPerDay - - /// - public static VolumeFlow MillionUsGallonsPerDay(this T value) => VolumeFlow.FromMillionUsGallonsPerDay(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? MillionUsGallonsPerDay(this T? value) where T : struct => VolumeFlow.FromMillionUsGallonsPerDay(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region NanolitersPerMinute - - /// - public static VolumeFlow NanolitersPerMinute(this T value) => VolumeFlow.FromNanolitersPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? NanolitersPerMinute(this T? value) where T : struct => VolumeFlow.FromNanolitersPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OilBarrelsPerDay - - /// - public static VolumeFlow OilBarrelsPerDay(this T value) => VolumeFlow.FromOilBarrelsPerDay(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? OilBarrelsPerDay(this T? value) where T : struct => VolumeFlow.FromOilBarrelsPerDay(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OilBarrelsPerHour - - /// - public static VolumeFlow OilBarrelsPerHour(this T value) => VolumeFlow.FromOilBarrelsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? OilBarrelsPerHour(this T? value) where T : struct => VolumeFlow.FromOilBarrelsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region OilBarrelsPerMinute - - /// - public static VolumeFlow OilBarrelsPerMinute(this T value) => VolumeFlow.FromOilBarrelsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? OilBarrelsPerMinute(this T? value) where T : struct => VolumeFlow.FromOilBarrelsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerHour - - /// - public static VolumeFlow UsGallonsPerHour(this T value) => VolumeFlow.FromUsGallonsPerHour(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? UsGallonsPerHour(this T? value) where T : struct => VolumeFlow.FromUsGallonsPerHour(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerMinute - - /// - public static VolumeFlow UsGallonsPerMinute(this T value) => VolumeFlow.FromUsGallonsPerMinute(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? UsGallonsPerMinute(this T? value) where T : struct => VolumeFlow.FromUsGallonsPerMinute(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - #region UsGallonsPerSecond - - /// - public static VolumeFlow UsGallonsPerSecond(this T value) => VolumeFlow.FromUsGallonsPerSecond(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? UsGallonsPerSecond(this T? value) where T : struct => VolumeFlow.FromUsGallonsPerSecond(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - - } -} -#endif diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs index e20250be5b..84ccd613a6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,132 +49,314 @@ namespace UnitsNet /// /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Acceleration : IComparable, IComparable + public partial struct Acceleration : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Acceleration from nullable CentimetersPerSecondSquared. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromCentimetersPerSecondSquared(QuantityValue? centimeterspersecondsquared) + private readonly AccelerationUnit? _unit; + + static Acceleration() { - return centimeterspersecondsquared.HasValue ? FromCentimetersPerSecondSquared(centimeterspersecondsquared.Value) : default(Acceleration?); + BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); } /// - /// Get nullable Acceleration from nullable DecimetersPerSecondSquared. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromDecimetersPerSecondSquared(QuantityValue? decimeterspersecondsquared) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Acceleration(double numericValue, AccelerationUnit unit) { - return decimeterspersecondsquared.HasValue ? FromDecimetersPerSecondSquared(decimeterspersecondsquared.Value) : default(Acceleration?); + if(unit == AccelerationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. + /// + public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; + + /// + /// Represents the largest possible value of Acceleration + /// + public static Acceleration MaxValue => new Acceleration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Acceleration + /// + public static Acceleration MinValue => new Acceleration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Acceleration; + + /// + /// All units of measurement for the Acceleration quantity. + /// + public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// + public static Acceleration Zero => new Acceleration(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Acceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Acceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Acceleration in CentimetersPerSecondSquared. + /// + public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); + + /// + /// Get Acceleration in DecimetersPerSecondSquared. + /// + public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); + + /// + /// Get Acceleration in FeetPerSecondSquared. + /// + public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); + + /// + /// Get Acceleration in InchesPerSecondSquared. + /// + public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); + + /// + /// Get Acceleration in KilometersPerSecondSquared. + /// + public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); + + /// + /// Get Acceleration in KnotsPerHour. + /// + public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); + + /// + /// Get Acceleration in KnotsPerMinute. + /// + public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); + + /// + /// Get Acceleration in KnotsPerSecond. + /// + public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); + + /// + /// Get Acceleration in MetersPerSecondSquared. + /// + public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); + + /// + /// Get Acceleration in MicrometersPerSecondSquared. + /// + public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); + + /// + /// Get Acceleration in MillimetersPerSecondSquared. + /// + public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); + /// - /// Get nullable Acceleration from nullable FeetPerSecondSquared. + /// Get Acceleration in NanometersPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromFeetPerSecondSquared(QuantityValue? feetpersecondsquared) + public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); + + /// + /// Get Acceleration in StandardGravity. + /// + public double StandardGravity => As(AccelerationUnit.StandardGravity); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AccelerationUnit unit) { - return feetpersecondsquared.HasValue ? FromFeetPerSecondSquared(feetpersecondsquared.Value) : default(Acceleration?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Acceleration from nullable InchesPerSecondSquared. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromInchesPerSecondSquared(QuantityValue? inchespersecondsquared) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] IFormatProvider provider) { - return inchespersecondsquared.HasValue ? FromInchesPerSecondSquared(inchespersecondsquared.Value) : default(Acceleration?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Acceleration from nullable KilometersPerSecondSquared. + /// Get Acceleration from CentimetersPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromKilometersPerSecondSquared(QuantityValue? kilometerspersecondsquared) + /// If value is NaN or Infinity. + public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) { - return kilometerspersecondsquared.HasValue ? FromKilometersPerSecondSquared(kilometerspersecondsquared.Value) : default(Acceleration?); + double value = (double) centimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable KnotsPerHour. + /// Get Acceleration from DecimetersPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromKnotsPerHour(QuantityValue? knotsperhour) + /// If value is NaN or Infinity. + public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) { - return knotsperhour.HasValue ? FromKnotsPerHour(knotsperhour.Value) : default(Acceleration?); + double value = (double) decimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable KnotsPerMinute. + /// Get Acceleration from FeetPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromKnotsPerMinute(QuantityValue? knotsperminute) + /// If value is NaN or Infinity. + public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) { - return knotsperminute.HasValue ? FromKnotsPerMinute(knotsperminute.Value) : default(Acceleration?); + double value = (double) feetpersecondsquared; + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable KnotsPerSecond. + /// Get Acceleration from InchesPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromKnotsPerSecond(QuantityValue? knotspersecond) + /// If value is NaN or Infinity. + public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) { - return knotspersecond.HasValue ? FromKnotsPerSecond(knotspersecond.Value) : default(Acceleration?); + double value = (double) inchespersecondsquared; + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable MetersPerSecondSquared. + /// Get Acceleration from KilometersPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromMetersPerSecondSquared(QuantityValue? meterspersecondsquared) + /// If value is NaN or Infinity. + public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) { - return meterspersecondsquared.HasValue ? FromMetersPerSecondSquared(meterspersecondsquared.Value) : default(Acceleration?); + double value = (double) kilometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable MicrometersPerSecondSquared. + /// Get Acceleration from KnotsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromMicrometersPerSecondSquared(QuantityValue? micrometerspersecondsquared) + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) { - return micrometerspersecondsquared.HasValue ? FromMicrometersPerSecondSquared(micrometerspersecondsquared.Value) : default(Acceleration?); + double value = (double) knotsperhour; + return new Acceleration(value, AccelerationUnit.KnotPerHour); } - /// - /// Get nullable Acceleration from nullable MillimetersPerSecondSquared. + /// Get Acceleration from KnotsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromMillimetersPerSecondSquared(QuantityValue? millimeterspersecondsquared) + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) { - return millimeterspersecondsquared.HasValue ? FromMillimetersPerSecondSquared(millimeterspersecondsquared.Value) : default(Acceleration?); + double value = (double) knotsperminute; + return new Acceleration(value, AccelerationUnit.KnotPerMinute); } - /// - /// Get nullable Acceleration from nullable NanometersPerSecondSquared. + /// Get Acceleration from KnotsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromNanometersPerSecondSquared(QuantityValue? nanometerspersecondsquared) + /// If value is NaN or Infinity. + public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) { - return nanometerspersecondsquared.HasValue ? FromNanometersPerSecondSquared(nanometerspersecondsquared.Value) : default(Acceleration?); + double value = (double) knotspersecond; + return new Acceleration(value, AccelerationUnit.KnotPerSecond); + } + /// + /// Get Acceleration from MetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) + { + double value = (double) meterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); + } + /// + /// Get Acceleration from MicrometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) + { + double value = (double) micrometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); + } + /// + /// Get Acceleration from MillimetersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) + { + double value = (double) millimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); + } + /// + /// Get Acceleration from NanometersPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) + { + double value = (double) nanometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); } - /// - /// Get nullable Acceleration from nullable StandardGravity. + /// Get Acceleration from StandardGravity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Acceleration? FromStandardGravity(QuantityValue? standardgravity) + /// If value is NaN or Infinity. + public static Acceleration FromStandardGravity(QuantityValue standardgravity) { - return standardgravity.HasValue ? FromStandardGravity(standardgravity.Value) : default(Acceleration?); + double value = (double) standardgravity; + return new Acceleration(value, AccelerationUnit.StandardGravity); } /// @@ -185,28 +365,156 @@ public partial struct Acceleration : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Acceleration unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Acceleration? From(QuantityValue? value, AccelerationUnit fromUnit) + public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) { - return value.HasValue ? new Acceleration((double)value.Value, fromUnit) : default(Acceleration?); + return new Acceleration((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Acceleration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Acceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Acceleration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AccelerationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AccelerationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static Acceleration operator -(Acceleration right) @@ -246,6 +554,8 @@ public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(Acceleration left, Acceleration right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -266,180 +576,240 @@ public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Acceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Acceleration left, Acceleration right) + public static bool operator ==(Acceleration left, Acceleration right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Acceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Acceleration left, Acceleration right) + public static bool operator !=(Acceleration left, Acceleration right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Acceleration other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Acceleration Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Acceleration other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AccelerationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersPerSecondSquared(x.MetersPerSecondSquared + y.MetersPerSecondSquared)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Acceleration result) + /// A hash code for the current Acceleration. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Acceleration); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AccelerationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Acceleration to another Acceleration with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Acceleration with the specified unit. + public Acceleration ToUnit(AccelerationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Acceleration(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; + case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; + case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; + case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; + case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return _value; + case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; + case AccelerationUnit.StandardGravity: return _value*9.80665; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(AccelerationUnit unit) + { + if(Unit == unit) + return _value; - if (unit == AccelerationUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; + case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; + case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; + case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; + case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; + case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; + case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AccelerationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs index 8b15a3e79a..90bf50a26d 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,150 +49,342 @@ namespace UnitsNet /// /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct AmountOfSubstance : IComparable, IComparable + public partial struct AmountOfSubstance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable AmountOfSubstance from nullable Centimoles. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromCentimoles(QuantityValue? centimoles) + private readonly AmountOfSubstanceUnit? _unit; + + static AmountOfSubstance() { - return centimoles.HasValue ? FromCentimoles(centimoles.Value) : default(AmountOfSubstance?); + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); } /// - /// Get nullable AmountOfSubstance from nullable CentipoundMoles. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromCentipoundMoles(QuantityValue? centipoundmoles) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public AmountOfSubstance(double numericValue, AmountOfSubstanceUnit unit) { - return centipoundmoles.HasValue ? FromCentipoundMoles(centipoundmoles.Value) : default(AmountOfSubstance?); + if(unit == AmountOfSubstanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. + /// + public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; + + /// + /// Represents the largest possible value of AmountOfSubstance + /// + public static AmountOfSubstance MaxValue => new AmountOfSubstance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AmountOfSubstance + /// + public static AmountOfSubstance MinValue => new AmountOfSubstance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AmountOfSubstance; + + /// + /// All units of measurement for the AmountOfSubstance quantity. + /// + public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Mole. + /// + public static AmountOfSubstance Zero => new AmountOfSubstance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmountOfSubstance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AmountOfSubstance in Centimoles. + /// + public double Centimoles => As(AmountOfSubstanceUnit.Centimole); + + /// + /// Get AmountOfSubstance in CentipoundMoles. + /// + public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); + + /// + /// Get AmountOfSubstance in Decimoles. + /// + public double Decimoles => As(AmountOfSubstanceUnit.Decimole); + + /// + /// Get AmountOfSubstance in DecipoundMoles. + /// + public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); + + /// + /// Get AmountOfSubstance in Kilomoles. + /// + public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); + + /// + /// Get AmountOfSubstance in KilopoundMoles. + /// + public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); + + /// + /// Get AmountOfSubstance in Megamoles. + /// + public double Megamoles => As(AmountOfSubstanceUnit.Megamole); + + /// + /// Get AmountOfSubstance in Micromoles. + /// + public double Micromoles => As(AmountOfSubstanceUnit.Micromole); + + /// + /// Get AmountOfSubstance in MicropoundMoles. + /// + public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); + + /// + /// Get AmountOfSubstance in Millimoles. + /// + public double Millimoles => As(AmountOfSubstanceUnit.Millimole); + + /// + /// Get AmountOfSubstance in MillipoundMoles. + /// + public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); + + /// + /// Get AmountOfSubstance in Moles. + /// + public double Moles => As(AmountOfSubstanceUnit.Mole); + + /// + /// Get AmountOfSubstance in Nanomoles. + /// + public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); + /// - /// Get nullable AmountOfSubstance from nullable Decimoles. + /// Get AmountOfSubstance in NanopoundMoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromDecimoles(QuantityValue? decimoles) + public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); + + /// + /// Get AmountOfSubstance in PoundMoles. + /// + public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmountOfSubstanceUnit unit) { - return decimoles.HasValue ? FromDecimoles(decimoles.Value) : default(AmountOfSubstance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable AmountOfSubstance from nullable DecipoundMoles. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromDecipoundMoles(QuantityValue? decipoundmoles) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider) { - return decipoundmoles.HasValue ? FromDecipoundMoles(decipoundmoles.Value) : default(AmountOfSubstance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable AmountOfSubstance from nullable Kilomoles. + /// Get AmountOfSubstance from Centimoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromKilomoles(QuantityValue? kilomoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) { - return kilomoles.HasValue ? FromKilomoles(kilomoles.Value) : default(AmountOfSubstance?); + double value = (double) centimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); } - /// - /// Get nullable AmountOfSubstance from nullable KilopoundMoles. + /// Get AmountOfSubstance from CentipoundMoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromKilopoundMoles(QuantityValue? kilopoundmoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) { - return kilopoundmoles.HasValue ? FromKilopoundMoles(kilopoundmoles.Value) : default(AmountOfSubstance?); + double value = (double) centipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); } - /// - /// Get nullable AmountOfSubstance from nullable Megamoles. + /// Get AmountOfSubstance from Decimoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMegamoles(QuantityValue? megamoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) { - return megamoles.HasValue ? FromMegamoles(megamoles.Value) : default(AmountOfSubstance?); + double value = (double) decimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); } - /// - /// Get nullable AmountOfSubstance from nullable Micromoles. + /// Get AmountOfSubstance from DecipoundMoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMicromoles(QuantityValue? micromoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) { - return micromoles.HasValue ? FromMicromoles(micromoles.Value) : default(AmountOfSubstance?); + double value = (double) decipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); } - /// - /// Get nullable AmountOfSubstance from nullable MicropoundMoles. + /// Get AmountOfSubstance from Kilomoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMicropoundMoles(QuantityValue? micropoundmoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) { - return micropoundmoles.HasValue ? FromMicropoundMoles(micropoundmoles.Value) : default(AmountOfSubstance?); + double value = (double) kilomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); } - /// - /// Get nullable AmountOfSubstance from nullable Millimoles. + /// Get AmountOfSubstance from KilopoundMoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMillimoles(QuantityValue? millimoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) { - return millimoles.HasValue ? FromMillimoles(millimoles.Value) : default(AmountOfSubstance?); + double value = (double) kilopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); } - /// - /// Get nullable AmountOfSubstance from nullable MillipoundMoles. + /// Get AmountOfSubstance from Megamoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMillipoundMoles(QuantityValue? millipoundmoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMegamoles(QuantityValue megamoles) { - return millipoundmoles.HasValue ? FromMillipoundMoles(millipoundmoles.Value) : default(AmountOfSubstance?); + double value = (double) megamoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); } - /// - /// Get nullable AmountOfSubstance from nullable Moles. + /// Get AmountOfSubstance from Micromoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromMoles(QuantityValue? moles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) { - return moles.HasValue ? FromMoles(moles.Value) : default(AmountOfSubstance?); + double value = (double) micromoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); } - /// - /// Get nullable AmountOfSubstance from nullable Nanomoles. + /// Get AmountOfSubstance from MicropoundMoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromNanomoles(QuantityValue? nanomoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) { - return nanomoles.HasValue ? FromNanomoles(nanomoles.Value) : default(AmountOfSubstance?); + double value = (double) micropoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); } - /// - /// Get nullable AmountOfSubstance from nullable NanopoundMoles. + /// Get AmountOfSubstance from Millimoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromNanopoundMoles(QuantityValue? nanopoundmoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) { - return nanopoundmoles.HasValue ? FromNanopoundMoles(nanopoundmoles.Value) : default(AmountOfSubstance?); + double value = (double) millimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); + } + /// + /// Get AmountOfSubstance from MillipoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) + { + double value = (double) millipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); + } + /// + /// Get AmountOfSubstance from Moles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromMoles(QuantityValue moles) + { + double value = (double) moles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); } - /// - /// Get nullable AmountOfSubstance from nullable PoundMoles. + /// Get AmountOfSubstance from Nanomoles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmountOfSubstance? FromPoundMoles(QuantityValue? poundmoles) + /// If value is NaN or Infinity. + public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) { - return poundmoles.HasValue ? FromPoundMoles(poundmoles.Value) : default(AmountOfSubstance?); + double value = (double) nanomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); + } + /// + /// Get AmountOfSubstance from NanopoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) + { + double value = (double) nanopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); + } + /// + /// Get AmountOfSubstance from PoundMoles. + /// + /// If value is NaN or Infinity. + public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) + { + double value = (double) poundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); } /// @@ -203,28 +393,156 @@ public partial struct AmountOfSubstance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// AmountOfSubstance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmountOfSubstance? From(QuantityValue? value, AmountOfSubstanceUnit fromUnit) + public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) { - return value.HasValue ? new AmountOfSubstance((double)value.Value, fromUnit) : default(AmountOfSubstance?); + return new AmountOfSubstance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static AmountOfSubstance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmountOfSubstance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AmountOfSubstanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AmountOfSubstanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static AmountOfSubstance operator -(AmountOfSubstance right) @@ -264,6 +582,8 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] IFo #endregion + #region Equality / IComparable + public static bool operator <=(AmountOfSubstance left, AmountOfSubstance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -284,180 +604,244 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] IFo return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmountOfSubstance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) + public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmountOfSubstance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) + public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(AmountOfSubstance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmountOfSubstance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AmountOfSubstanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMoles(x.Moles + y.Moles)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmountOfSubstance result) + /// A hash code for the current AmountOfSubstance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(AmountOfSubstance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmountOfSubstanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A AmountOfSubstance with the specified unit. + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new AmountOfSubstance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == AmountOfSubstanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmountOfSubstanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs index 7feadaf7bc..5c92424eee 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,188 @@ namespace UnitsNet /// /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct AmplitudeRatio : IComparable, IComparable + public partial struct AmplitudeRatio : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly AmplitudeRatioUnit? _unit; + + static AmplitudeRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } /// - /// Get nullable AmplitudeRatio from nullable DecibelMicrovolts. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmplitudeRatio? FromDecibelMicrovolts(QuantityValue? decibelmicrovolts) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public AmplitudeRatio(double numericValue, AmplitudeRatioUnit unit) { - return decibelmicrovolts.HasValue ? FromDecibelMicrovolts(decibelmicrovolts.Value) : default(AmplitudeRatio?); + if(unit == AmplitudeRatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. + /// + public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; + + /// + /// Represents the largest possible value of AmplitudeRatio + /// + public static AmplitudeRatio MaxValue => new AmplitudeRatio(double.MaxValue, BaseUnit); + /// - /// Get nullable AmplitudeRatio from nullable DecibelMillivolts. + /// Represents the smallest possible value of AmplitudeRatio /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmplitudeRatio? FromDecibelMillivolts(QuantityValue? decibelmillivolts) + public static AmplitudeRatio MinValue => new AmplitudeRatio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AmplitudeRatio; + + /// + /// All units of measurement for the AmplitudeRatio quantity. + /// + public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. + /// + public static AmplitudeRatio Zero => new AmplitudeRatio(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AmplitudeRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AmplitudeRatio in DecibelMicrovolts. + /// + public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); + + /// + /// Get AmplitudeRatio in DecibelMillivolts. + /// + public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); + + /// + /// Get AmplitudeRatio in DecibelsUnloaded. + /// + public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); + + /// + /// Get AmplitudeRatio in DecibelVolts. + /// + public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AmplitudeRatioUnit unit) { - return decibelmillivolts.HasValue ? FromDecibelMillivolts(decibelmillivolts.Value) : default(AmplitudeRatio?); + return GetAbbreviation(unit, null); } /// - /// Get nullable AmplitudeRatio from nullable DecibelsUnloaded. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmplitudeRatio? FromDecibelsUnloaded(QuantityValue? decibelsunloaded) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider) { - return decibelsunloaded.HasValue ? FromDecibelsUnloaded(decibelsunloaded.Value) : default(AmplitudeRatio?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get AmplitudeRatio from DecibelMicrovolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) + { + double value = (double) decibelmicrovolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); + } + /// + /// Get AmplitudeRatio from DecibelMillivolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) + { + double value = (double) decibelmillivolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); + } /// - /// Get nullable AmplitudeRatio from nullable DecibelVolts. + /// Get AmplitudeRatio from DecibelsUnloaded. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AmplitudeRatio? FromDecibelVolts(QuantityValue? decibelvolts) + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) { - return decibelvolts.HasValue ? FromDecibelVolts(decibelvolts.Value) : default(AmplitudeRatio?); + double value = (double) decibelsunloaded; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); + } + /// + /// Get AmplitudeRatio from DecibelVolts. + /// + /// If value is NaN or Infinity. + public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) + { + double value = (double) decibelvolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); } /// @@ -104,28 +239,156 @@ public partial struct AmplitudeRatio : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// AmplitudeRatio unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AmplitudeRatio? From(QuantityValue? value, AmplitudeRatioUnit fromUnit) + public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) { - return value.HasValue ? new AmplitudeRatio((double)value.Value, fromUnit) : default(AmplitudeRatio?); + return new AmplitudeRatio((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static AmplitudeRatio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmplitudeRatio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AmplitudeRatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AmplitudeRatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Logarithmic Arithmetic Operators public static AmplitudeRatio operator -(AmplitudeRatio right) @@ -173,6 +436,8 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(AmplitudeRatio left, AmplitudeRatio right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -193,180 +458,222 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmplitudeRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) + public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AmplitudeRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) + public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(AmplitudeRatio other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmplitudeRatio Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AmplitudeRatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibelVolts(x.DecibelVolts + y.DecibelVolts)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AmplitudeRatio result) + /// A hash code for the current AmplitudeRatio. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(AmplitudeRatio); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmplitudeRatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A AmplitudeRatio with the specified unit. + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new AmplitudeRatio(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == AmplitudeRatioUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmplitudeRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs index d145b00061..da67ba174f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,141 +49,328 @@ namespace UnitsNet /// /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Angle : IComparable, IComparable + public partial struct Angle : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Angle from nullable Arcminutes. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromArcminutes(QuantityValue? arcminutes) + private readonly AngleUnit? _unit; + + static Angle() { - return arcminutes.HasValue ? FromArcminutes(arcminutes.Value) : default(Angle?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable Angle from nullable Arcseconds. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromArcseconds(QuantityValue? arcseconds) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Angle(double numericValue, AngleUnit unit) { - return arcseconds.HasValue ? FromArcseconds(arcseconds.Value) : default(Angle?); + if(unit == AngleUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Angle, which is Degree. All conversions go via this value. + /// + public static AngleUnit BaseUnit => AngleUnit.Degree; + + /// + /// Represents the largest possible value of Angle + /// + public static Angle MaxValue => new Angle(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Angle + /// + public static Angle MinValue => new Angle(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Angle; + + /// + /// All units of measurement for the Angle quantity. + /// + public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Degree. + /// + public static Angle Zero => new Angle(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Angle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Angle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Angle in Arcminutes. + /// + public double Arcminutes => As(AngleUnit.Arcminute); + + /// + /// Get Angle in Arcseconds. + /// + public double Arcseconds => As(AngleUnit.Arcsecond); + + /// + /// Get Angle in Centiradians. + /// + public double Centiradians => As(AngleUnit.Centiradian); + + /// + /// Get Angle in Deciradians. + /// + public double Deciradians => As(AngleUnit.Deciradian); + + /// + /// Get Angle in Degrees. + /// + public double Degrees => As(AngleUnit.Degree); + + /// + /// Get Angle in Gradians. + /// + public double Gradians => As(AngleUnit.Gradian); + + /// + /// Get Angle in Microdegrees. + /// + public double Microdegrees => As(AngleUnit.Microdegree); + + /// + /// Get Angle in Microradians. + /// + public double Microradians => As(AngleUnit.Microradian); + + /// + /// Get Angle in Millidegrees. + /// + public double Millidegrees => As(AngleUnit.Millidegree); + + /// + /// Get Angle in Milliradians. + /// + public double Milliradians => As(AngleUnit.Milliradian); + + /// + /// Get Angle in Nanodegrees. + /// + public double Nanodegrees => As(AngleUnit.Nanodegree); + + /// + /// Get Angle in Nanoradians. + /// + public double Nanoradians => As(AngleUnit.Nanoradian); + + /// + /// Get Angle in Radians. + /// + public double Radians => As(AngleUnit.Radian); + /// - /// Get nullable Angle from nullable Centiradians. + /// Get Angle in Revolutions. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromCentiradians(QuantityValue? centiradians) + public double Revolutions => As(AngleUnit.Revolution); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AngleUnit unit) { - return centiradians.HasValue ? FromCentiradians(centiradians.Value) : default(Angle?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Angle from nullable Deciradians. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromDeciradians(QuantityValue? deciradians) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AngleUnit unit, [CanBeNull] IFormatProvider provider) { - return deciradians.HasValue ? FromDeciradians(deciradians.Value) : default(Angle?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Angle from nullable Degrees. + /// Get Angle from Arcminutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromDegrees(QuantityValue? degrees) + /// If value is NaN or Infinity. + public static Angle FromArcminutes(QuantityValue arcminutes) { - return degrees.HasValue ? FromDegrees(degrees.Value) : default(Angle?); + double value = (double) arcminutes; + return new Angle(value, AngleUnit.Arcminute); } - /// - /// Get nullable Angle from nullable Gradians. + /// Get Angle from Arcseconds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromGradians(QuantityValue? gradians) + /// If value is NaN or Infinity. + public static Angle FromArcseconds(QuantityValue arcseconds) { - return gradians.HasValue ? FromGradians(gradians.Value) : default(Angle?); + double value = (double) arcseconds; + return new Angle(value, AngleUnit.Arcsecond); } - /// - /// Get nullable Angle from nullable Microdegrees. + /// Get Angle from Centiradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromMicrodegrees(QuantityValue? microdegrees) + /// If value is NaN or Infinity. + public static Angle FromCentiradians(QuantityValue centiradians) { - return microdegrees.HasValue ? FromMicrodegrees(microdegrees.Value) : default(Angle?); + double value = (double) centiradians; + return new Angle(value, AngleUnit.Centiradian); } - /// - /// Get nullable Angle from nullable Microradians. + /// Get Angle from Deciradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromMicroradians(QuantityValue? microradians) + /// If value is NaN or Infinity. + public static Angle FromDeciradians(QuantityValue deciradians) { - return microradians.HasValue ? FromMicroradians(microradians.Value) : default(Angle?); + double value = (double) deciradians; + return new Angle(value, AngleUnit.Deciradian); } - /// - /// Get nullable Angle from nullable Millidegrees. + /// Get Angle from Degrees. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromMillidegrees(QuantityValue? millidegrees) + /// If value is NaN or Infinity. + public static Angle FromDegrees(QuantityValue degrees) { - return millidegrees.HasValue ? FromMillidegrees(millidegrees.Value) : default(Angle?); + double value = (double) degrees; + return new Angle(value, AngleUnit.Degree); } - /// - /// Get nullable Angle from nullable Milliradians. + /// Get Angle from Gradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromMilliradians(QuantityValue? milliradians) + /// If value is NaN or Infinity. + public static Angle FromGradians(QuantityValue gradians) { - return milliradians.HasValue ? FromMilliradians(milliradians.Value) : default(Angle?); + double value = (double) gradians; + return new Angle(value, AngleUnit.Gradian); } - /// - /// Get nullable Angle from nullable Nanodegrees. + /// Get Angle from Microdegrees. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromNanodegrees(QuantityValue? nanodegrees) + /// If value is NaN or Infinity. + public static Angle FromMicrodegrees(QuantityValue microdegrees) { - return nanodegrees.HasValue ? FromNanodegrees(nanodegrees.Value) : default(Angle?); + double value = (double) microdegrees; + return new Angle(value, AngleUnit.Microdegree); } - /// - /// Get nullable Angle from nullable Nanoradians. + /// Get Angle from Microradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromNanoradians(QuantityValue? nanoradians) + /// If value is NaN or Infinity. + public static Angle FromMicroradians(QuantityValue microradians) { - return nanoradians.HasValue ? FromNanoradians(nanoradians.Value) : default(Angle?); + double value = (double) microradians; + return new Angle(value, AngleUnit.Microradian); } - /// - /// Get nullable Angle from nullable Radians. + /// Get Angle from Millidegrees. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromRadians(QuantityValue? radians) + /// If value is NaN or Infinity. + public static Angle FromMillidegrees(QuantityValue millidegrees) { - return radians.HasValue ? FromRadians(radians.Value) : default(Angle?); + double value = (double) millidegrees; + return new Angle(value, AngleUnit.Millidegree); + } + /// + /// Get Angle from Milliradians. + /// + /// If value is NaN or Infinity. + public static Angle FromMilliradians(QuantityValue milliradians) + { + double value = (double) milliradians; + return new Angle(value, AngleUnit.Milliradian); + } + /// + /// Get Angle from Nanodegrees. + /// + /// If value is NaN or Infinity. + public static Angle FromNanodegrees(QuantityValue nanodegrees) + { + double value = (double) nanodegrees; + return new Angle(value, AngleUnit.Nanodegree); } - /// - /// Get nullable Angle from nullable Revolutions. + /// Get Angle from Nanoradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Angle? FromRevolutions(QuantityValue? revolutions) + /// If value is NaN or Infinity. + public static Angle FromNanoradians(QuantityValue nanoradians) { - return revolutions.HasValue ? FromRevolutions(revolutions.Value) : default(Angle?); + double value = (double) nanoradians; + return new Angle(value, AngleUnit.Nanoradian); + } + /// + /// Get Angle from Radians. + /// + /// If value is NaN or Infinity. + public static Angle FromRadians(QuantityValue radians) + { + double value = (double) radians; + return new Angle(value, AngleUnit.Radian); + } + /// + /// Get Angle from Revolutions. + /// + /// If value is NaN or Infinity. + public static Angle FromRevolutions(QuantityValue revolutions) + { + double value = (double) revolutions; + return new Angle(value, AngleUnit.Revolution); } /// @@ -194,28 +379,156 @@ public partial struct Angle : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Angle unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Angle? From(QuantityValue? value, AngleUnit fromUnit) + public static Angle From(QuantityValue value, AngleUnit fromUnit) { - return value.HasValue ? new Angle((double)value.Value, fromUnit) : default(Angle?); + return new Angle((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AngleUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Angle Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Angle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Angle result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AngleUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AngleUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AngleUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Angle operator -(Angle right) @@ -255,6 +568,8 @@ public static string GetAbbreviation(AngleUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Angle left, Angle right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -275,180 +590,242 @@ public static string GetAbbreviation(AngleUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Angle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Angle left, Angle right) + public static bool operator ==(Angle left, Angle right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Angle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Angle left, Angle right) + public static bool operator !=(Angle left, Angle right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Angle other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Angle Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AngleUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegrees(x.Degrees + y.Degrees)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Angle result) + /// A hash code for the current Angle. + public override int GetHashCode() + { + return new { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AngleUnit unit) { - provider = provider ?? UnitSystem.DefaultCulture; + if(Unit == unit) + return Convert.ToDouble(Value); - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Angle); - return false; - } + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Angle to another Angle with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Angle with the specified unit. + public Angle ToUnit(AngleUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Angle(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AngleUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case AngleUnit.Arcminute: return _value/60; + case AngleUnit.Arcsecond: return _value/3600; + case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; + case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; + case AngleUnit.Degree: return _value; + case AngleUnit.Gradian: return _value*0.9; + case AngleUnit.Microdegree: return (_value) * 1e-6d; + case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; + case AngleUnit.Millidegree: return (_value) * 1e-3d; + case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; + case AngleUnit.Nanodegree: return (_value) * 1e-9d; + case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; + case AngleUnit.Radian: return _value*180/Math.PI; + case AngleUnit.Revolution: return _value*360; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(AngleUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == AngleUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AngleUnit.Arcminute: return baseUnitValue*60; + case AngleUnit.Arcsecond: return baseUnitValue*3600; + case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; + case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; + case AngleUnit.Degree: return baseUnitValue; + case AngleUnit.Gradian: return baseUnitValue/0.9; + case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; + case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; + case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; + case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; + case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; + case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; + case AngleUnit.Radian: return baseUnitValue/180*Math.PI; + case AngleUnit.Revolution: return baseUnitValue/360; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AngleUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs index b2e576446d..d9ffd9f485 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ApparentEnergy : IComparable, IComparable + public partial struct ApparentEnergy : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentEnergyUnit? _unit; + + static ApparentEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ApparentEnergy(double numericValue, ApparentEnergyUnit unit) + { + if(unit == ApparentEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. + /// + public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; + + /// + /// Represents the largest possible value of ApparentEnergy + /// + public static ApparentEnergy MaxValue => new ApparentEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ApparentEnergy + /// + public static ApparentEnergy MinValue => new ApparentEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ApparentEnergy; + + /// + /// All units of measurement for the ApparentEnergy quantity. + /// + public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. + /// + public static ApparentEnergy Zero => new ApparentEnergy(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable ApparentEnergy from nullable KilovoltampereHours. + /// Get ApparentEnergy in KilovoltampereHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentEnergy? FromKilovoltampereHours(QuantityValue? kilovoltamperehours) + public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); + + /// + /// Get ApparentEnergy in MegavoltampereHours. + /// + public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); + + /// + /// Get ApparentEnergy in VoltampereHours. + /// + public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentEnergyUnit unit) { - return kilovoltamperehours.HasValue ? FromKilovoltampereHours(kilovoltamperehours.Value) : default(ApparentEnergy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ApparentEnergy from nullable MegavoltampereHours. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentEnergy? FromMegavoltampereHours(QuantityValue? megavoltamperehours) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider) { - return megavoltamperehours.HasValue ? FromMegavoltampereHours(megavoltamperehours.Value) : default(ApparentEnergy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentEnergy from KilovoltampereHours. + /// + /// If value is NaN or Infinity. + public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) + { + double value = (double) kilovoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); + } /// - /// Get nullable ApparentEnergy from nullable VoltampereHours. + /// Get ApparentEnergy from MegavoltampereHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentEnergy? FromVoltampereHours(QuantityValue? voltamperehours) + /// If value is NaN or Infinity. + public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) { - return voltamperehours.HasValue ? FromVoltampereHours(voltamperehours.Value) : default(ApparentEnergy?); + double value = (double) megavoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); + } + /// + /// Get ApparentEnergy from VoltampereHours. + /// + /// If value is NaN or Infinity. + public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) + { + double value = (double) voltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); } /// @@ -95,28 +225,156 @@ public partial struct ApparentEnergy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ApparentEnergy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentEnergy? From(QuantityValue? value, ApparentEnergyUnit fromUnit) + public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) { - return value.HasValue ? new ApparentEnergy((double)value.Value, fromUnit) : default(ApparentEnergy?); + return new ApparentEnergy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ApparentEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ApparentEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ApparentEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ApparentEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ApparentEnergy operator -(ApparentEnergy right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(ApparentEnergy left, ApparentEnergy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ApparentEnergy left, ApparentEnergy right) + public static bool operator ==(ApparentEnergy left, ApparentEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ApparentEnergy left, ApparentEnergy right) + public static bool operator !=(ApparentEnergy left, ApparentEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ApparentEnergy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ApparentEnergy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ApparentEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltampereHours(x.VoltampereHours + y.VoltampereHours)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentEnergy result) + /// A hash code for the current ApparentEnergy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ApparentEnergy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ApparentEnergy with the specified unit. + public ApparentEnergy ToUnit(ApparentEnergyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ApparentEnergy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ApparentEnergyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs index 2c93a7aa65..339f0a85ed 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,188 @@ namespace UnitsNet /// /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ApparentPower : IComparable, IComparable + public partial struct ApparentPower : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentPowerUnit? _unit; + + static ApparentPower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } /// - /// Get nullable ApparentPower from nullable Gigavoltamperes. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentPower? FromGigavoltamperes(QuantityValue? gigavoltamperes) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ApparentPower(double numericValue, ApparentPowerUnit unit) { - return gigavoltamperes.HasValue ? FromGigavoltamperes(gigavoltamperes.Value) : default(ApparentPower?); + if(unit == ApparentPowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. + /// + public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; + + /// + /// Represents the largest possible value of ApparentPower + /// + public static ApparentPower MaxValue => new ApparentPower(double.MaxValue, BaseUnit); + /// - /// Get nullable ApparentPower from nullable Kilovoltamperes. + /// Represents the smallest possible value of ApparentPower /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentPower? FromKilovoltamperes(QuantityValue? kilovoltamperes) + public static ApparentPower MinValue => new ApparentPower(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ApparentPower; + + /// + /// All units of measurement for the ApparentPower quantity. + /// + public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. + /// + public static ApparentPower Zero => new ApparentPower(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ApparentPower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ApparentPower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ApparentPower in Gigavoltamperes. + /// + public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); + + /// + /// Get ApparentPower in Kilovoltamperes. + /// + public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); + + /// + /// Get ApparentPower in Megavoltamperes. + /// + public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); + + /// + /// Get ApparentPower in Voltamperes. + /// + public double Voltamperes => As(ApparentPowerUnit.Voltampere); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ApparentPowerUnit unit) { - return kilovoltamperes.HasValue ? FromKilovoltamperes(kilovoltamperes.Value) : default(ApparentPower?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ApparentPower from nullable Megavoltamperes. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentPower? FromMegavoltamperes(QuantityValue? megavoltamperes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider) { - return megavoltamperes.HasValue ? FromMegavoltamperes(megavoltamperes.Value) : default(ApparentPower?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ApparentPower from Gigavoltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) + { + double value = (double) gigavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); + } + /// + /// Get ApparentPower from Kilovoltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) + { + double value = (double) kilovoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); + } /// - /// Get nullable ApparentPower from nullable Voltamperes. + /// Get ApparentPower from Megavoltamperes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ApparentPower? FromVoltamperes(QuantityValue? voltamperes) + /// If value is NaN or Infinity. + public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) { - return voltamperes.HasValue ? FromVoltamperes(voltamperes.Value) : default(ApparentPower?); + double value = (double) megavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); + } + /// + /// Get ApparentPower from Voltamperes. + /// + /// If value is NaN or Infinity. + public static ApparentPower FromVoltamperes(QuantityValue voltamperes) + { + double value = (double) voltamperes; + return new ApparentPower(value, ApparentPowerUnit.Voltampere); } /// @@ -104,28 +239,156 @@ public partial struct ApparentPower : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ApparentPower unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ApparentPower? From(QuantityValue? value, ApparentPowerUnit fromUnit) + public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) { - return value.HasValue ? new ApparentPower((double)value.Value, fromUnit) : default(ApparentPower?); + return new ApparentPower((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ApparentPower Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ApparentPower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentPower result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ApparentPowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ApparentPowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ApparentPowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ApparentPowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ApparentPower operator -(ApparentPower right) @@ -165,6 +428,8 @@ public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(ApparentPower left, ApparentPower right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +450,222 @@ public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentPower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ApparentPower left, ApparentPower right) + public static bool operator ==(ApparentPower left, ApparentPower right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ApparentPower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ApparentPower left, ApparentPower right) + public static bool operator !=(ApparentPower left, ApparentPower right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ApparentPower other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentPower Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ApparentPower other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ApparentPowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltamperes(x.Voltamperes + y.Voltamperes)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ApparentPower result) + /// A hash code for the current ApparentPower. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ApparentPower); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentPowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ApparentPower to another ApparentPower with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ApparentPower with the specified unit. + public ApparentPower ToUnit(ApparentPowerUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ApparentPower(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentPowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ApparentPowerUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentPowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs index 415b6fe5bf..834ca4aa2e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,132 +49,314 @@ namespace UnitsNet /// /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Area : IComparable, IComparable + public partial struct Area : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Area from nullable Acres. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromAcres(QuantityValue? acres) + private readonly AreaUnit? _unit; + + static Area() { - return acres.HasValue ? FromAcres(acres.Value) : default(Area?); + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); } /// - /// Get nullable Area from nullable Hectares. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromHectares(QuantityValue? hectares) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Area(double numericValue, AreaUnit unit) { - return hectares.HasValue ? FromHectares(hectares.Value) : default(Area?); + if(unit == AreaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Area, which is SquareMeter. All conversions go via this value. + /// + public static AreaUnit BaseUnit => AreaUnit.SquareMeter; + + /// + /// Represents the largest possible value of Area + /// + public static Area MaxValue => new Area(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Area + /// + public static Area MinValue => new Area(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Area; + + /// + /// All units of measurement for the Area quantity. + /// + public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// + public static Area Zero => new Area(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Area.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Area.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Area in Acres. + /// + public double Acres => As(AreaUnit.Acre); + + /// + /// Get Area in Hectares. + /// + public double Hectares => As(AreaUnit.Hectare); + + /// + /// Get Area in SquareCentimeters. + /// + public double SquareCentimeters => As(AreaUnit.SquareCentimeter); + + /// + /// Get Area in SquareDecimeters. + /// + public double SquareDecimeters => As(AreaUnit.SquareDecimeter); + + /// + /// Get Area in SquareFeet. + /// + public double SquareFeet => As(AreaUnit.SquareFoot); + + /// + /// Get Area in SquareInches. + /// + public double SquareInches => As(AreaUnit.SquareInch); + + /// + /// Get Area in SquareKilometers. + /// + public double SquareKilometers => As(AreaUnit.SquareKilometer); + + /// + /// Get Area in SquareMeters. + /// + public double SquareMeters => As(AreaUnit.SquareMeter); + + /// + /// Get Area in SquareMicrometers. + /// + public double SquareMicrometers => As(AreaUnit.SquareMicrometer); + + /// + /// Get Area in SquareMiles. + /// + public double SquareMiles => As(AreaUnit.SquareMile); + + /// + /// Get Area in SquareMillimeters. + /// + public double SquareMillimeters => As(AreaUnit.SquareMillimeter); + /// - /// Get nullable Area from nullable SquareCentimeters. + /// Get Area in SquareYards. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareCentimeters(QuantityValue? squarecentimeters) + public double SquareYards => As(AreaUnit.SquareYard); + + /// + /// Get Area in UsSurveySquareFeet. + /// + public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaUnit unit) { - return squarecentimeters.HasValue ? FromSquareCentimeters(squarecentimeters.Value) : default(Area?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Area from nullable SquareDecimeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareDecimeters(QuantityValue? squaredecimeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AreaUnit unit, [CanBeNull] IFormatProvider provider) { - return squaredecimeters.HasValue ? FromSquareDecimeters(squaredecimeters.Value) : default(Area?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Area from nullable SquareFeet. + /// Get Area from Acres. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareFeet(QuantityValue? squarefeet) + /// If value is NaN or Infinity. + public static Area FromAcres(QuantityValue acres) { - return squarefeet.HasValue ? FromSquareFeet(squarefeet.Value) : default(Area?); + double value = (double) acres; + return new Area(value, AreaUnit.Acre); } - /// - /// Get nullable Area from nullable SquareInches. + /// Get Area from Hectares. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareInches(QuantityValue? squareinches) + /// If value is NaN or Infinity. + public static Area FromHectares(QuantityValue hectares) { - return squareinches.HasValue ? FromSquareInches(squareinches.Value) : default(Area?); + double value = (double) hectares; + return new Area(value, AreaUnit.Hectare); } - /// - /// Get nullable Area from nullable SquareKilometers. + /// Get Area from SquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareKilometers(QuantityValue? squarekilometers) + /// If value is NaN or Infinity. + public static Area FromSquareCentimeters(QuantityValue squarecentimeters) { - return squarekilometers.HasValue ? FromSquareKilometers(squarekilometers.Value) : default(Area?); + double value = (double) squarecentimeters; + return new Area(value, AreaUnit.SquareCentimeter); } - /// - /// Get nullable Area from nullable SquareMeters. + /// Get Area from SquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareMeters(QuantityValue? squaremeters) + /// If value is NaN or Infinity. + public static Area FromSquareDecimeters(QuantityValue squaredecimeters) { - return squaremeters.HasValue ? FromSquareMeters(squaremeters.Value) : default(Area?); + double value = (double) squaredecimeters; + return new Area(value, AreaUnit.SquareDecimeter); } - /// - /// Get nullable Area from nullable SquareMicrometers. + /// Get Area from SquareFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareMicrometers(QuantityValue? squaremicrometers) + /// If value is NaN or Infinity. + public static Area FromSquareFeet(QuantityValue squarefeet) { - return squaremicrometers.HasValue ? FromSquareMicrometers(squaremicrometers.Value) : default(Area?); + double value = (double) squarefeet; + return new Area(value, AreaUnit.SquareFoot); } - /// - /// Get nullable Area from nullable SquareMiles. + /// Get Area from SquareInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareMiles(QuantityValue? squaremiles) + /// If value is NaN or Infinity. + public static Area FromSquareInches(QuantityValue squareinches) { - return squaremiles.HasValue ? FromSquareMiles(squaremiles.Value) : default(Area?); + double value = (double) squareinches; + return new Area(value, AreaUnit.SquareInch); } - /// - /// Get nullable Area from nullable SquareMillimeters. + /// Get Area from SquareKilometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareMillimeters(QuantityValue? squaremillimeters) + /// If value is NaN or Infinity. + public static Area FromSquareKilometers(QuantityValue squarekilometers) { - return squaremillimeters.HasValue ? FromSquareMillimeters(squaremillimeters.Value) : default(Area?); + double value = (double) squarekilometers; + return new Area(value, AreaUnit.SquareKilometer); } - /// - /// Get nullable Area from nullable SquareYards. + /// Get Area from SquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromSquareYards(QuantityValue? squareyards) + /// If value is NaN or Infinity. + public static Area FromSquareMeters(QuantityValue squaremeters) { - return squareyards.HasValue ? FromSquareYards(squareyards.Value) : default(Area?); + double value = (double) squaremeters; + return new Area(value, AreaUnit.SquareMeter); + } + /// + /// Get Area from SquareMicrometers. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMicrometers(QuantityValue squaremicrometers) + { + double value = (double) squaremicrometers; + return new Area(value, AreaUnit.SquareMicrometer); + } + /// + /// Get Area from SquareMiles. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMiles(QuantityValue squaremiles) + { + double value = (double) squaremiles; + return new Area(value, AreaUnit.SquareMile); + } + /// + /// Get Area from SquareMillimeters. + /// + /// If value is NaN or Infinity. + public static Area FromSquareMillimeters(QuantityValue squaremillimeters) + { + double value = (double) squaremillimeters; + return new Area(value, AreaUnit.SquareMillimeter); + } + /// + /// Get Area from SquareYards. + /// + /// If value is NaN or Infinity. + public static Area FromSquareYards(QuantityValue squareyards) + { + double value = (double) squareyards; + return new Area(value, AreaUnit.SquareYard); } - /// - /// Get nullable Area from nullable UsSurveySquareFeet. + /// Get Area from UsSurveySquareFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Area? FromUsSurveySquareFeet(QuantityValue? ussurveysquarefeet) + /// If value is NaN or Infinity. + public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) { - return ussurveysquarefeet.HasValue ? FromUsSurveySquareFeet(ussurveysquarefeet.Value) : default(Area?); + double value = (double) ussurveysquarefeet; + return new Area(value, AreaUnit.UsSurveySquareFoot); } /// @@ -185,28 +365,156 @@ public partial struct Area : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Area unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Area? From(QuantityValue? value, AreaUnit fromUnit) + public static Area From(QuantityValue value, AreaUnit fromUnit) { - return value.HasValue ? new Area((double)value.Value, fromUnit) : default(Area?); + return new Area((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Area Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Area result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Area result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AreaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AreaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AreaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static Area operator -(Area right) @@ -246,6 +554,8 @@ public static string GetAbbreviation(AreaUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Area left, Area right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -266,180 +576,240 @@ public static string GetAbbreviation(AreaUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Area, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Area left, Area right) + public static bool operator ==(Area left, Area right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Area, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Area left, Area right) + public static bool operator !=(Area left, Area right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Area other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Area Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Area other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMeters(x.SquareMeters + y.SquareMeters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Area result) + /// A hash code for the current Area. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Area); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Area to another Area with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Area with the specified unit. + public Area ToUnit(AreaUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Area(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case AreaUnit.Acre: return _value*4046.85642; + case AreaUnit.Hectare: return _value*1e4; + case AreaUnit.SquareCentimeter: return _value*1e-4; + case AreaUnit.SquareDecimeter: return _value*1e-2; + case AreaUnit.SquareFoot: return _value*0.092903; + case AreaUnit.SquareInch: return _value*0.00064516; + case AreaUnit.SquareKilometer: return _value*1e6; + case AreaUnit.SquareMeter: return _value; + case AreaUnit.SquareMicrometer: return _value*1e-12; + case AreaUnit.SquareMile: return _value*2.59e6; + case AreaUnit.SquareMillimeter: return _value*1e-6; + case AreaUnit.SquareYard: return _value*0.836127; + case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(AreaUnit unit) + { + if(Unit == unit) + return _value; - if (unit == AreaUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AreaUnit.Acre: return baseUnitValue/4046.85642; + case AreaUnit.Hectare: return baseUnitValue/1e4; + case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; + case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; + case AreaUnit.SquareFoot: return baseUnitValue/0.092903; + case AreaUnit.SquareInch: return baseUnitValue/0.00064516; + case AreaUnit.SquareKilometer: return baseUnitValue/1e6; + case AreaUnit.SquareMeter: return baseUnitValue; + case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; + case AreaUnit.SquareMile: return baseUnitValue/2.59e6; + case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; + case AreaUnit.SquareYard: return baseUnitValue/0.836127; + case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AreaUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs index d78c8ae228..4d2aa8e3c4 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,146 @@ namespace UnitsNet /// /// The area density of a two-dimensional object is calculated as the mass per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct AreaDensity : IComparable, IComparable + public partial struct AreaDensity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaDensityUnit? _unit; + + static AreaDensity() + { + BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public AreaDensity(double numericValue, AreaDensityUnit unit) + { + if(unit == AreaDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. + /// + public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; + + /// + /// Represents the largest possible value of AreaDensity + /// + public static AreaDensity MaxValue => new AreaDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AreaDensity + /// + public static AreaDensity MinValue => new AreaDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AreaDensity; + + /// + /// All units of measurement for the AreaDensity quantity. + /// + public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// + public static AreaDensity Zero => new AreaDensity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaDensity in KilogramsPerSquareMeter. + /// + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable AreaDensity from nullable KilogramsPerSquareMeter. + /// Get AreaDensity from KilogramsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaDensity? FromKilogramsPerSquareMeter(QuantityValue? kilogramspersquaremeter) + /// If value is NaN or Infinity. + public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) { - return kilogramspersquaremeter.HasValue ? FromKilogramsPerSquareMeter(kilogramspersquaremeter.Value) : default(AreaDensity?); + double value = (double) kilogramspersquaremeter; + return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); } /// @@ -77,28 +197,156 @@ public partial struct AreaDensity : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// AreaDensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaDensity? From(QuantityValue? value, AreaDensityUnit fromUnit) + public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) { - return value.HasValue ? new AreaDensity((double)value.Value, fromUnit) : default(AreaDensity?); + return new AreaDensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static AreaDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AreaDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AreaDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AreaDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static AreaDensity operator -(AreaDensity right) @@ -138,6 +386,8 @@ public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(AreaDensity left, AreaDensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +408,216 @@ public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(AreaDensity left, AreaDensity right) + public static bool operator ==(AreaDensity left, AreaDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(AreaDensity left, AreaDensity right) + public static bool operator !=(AreaDensity left, AreaDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(AreaDensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaDensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(AreaDensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerSquareMeter(x.KilogramsPerSquareMeter + y.KilogramsPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaDensity result) + /// A hash code for the current AreaDensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(AreaDensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this AreaDensity to another AreaDensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A AreaDensity with the specified unit. + public AreaDensity ToUnit(AreaDensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new AreaDensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case AreaDensityUnit.KilogramPerSquareMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(AreaDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == AreaDensityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs index d7e2d82278..df5403d431 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,69 +49,216 @@ namespace UnitsNet /// /// A geometric property of an area that reflects how its points are distributed with regard to an axis. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct AreaMomentOfInertia : IComparable, IComparable + public partial struct AreaMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable AreaMomentOfInertia from nullable CentimetersToTheFourth. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromCentimetersToTheFourth(QuantityValue? centimeterstothefourth) + private readonly AreaMomentOfInertiaUnit? _unit; + + static AreaMomentOfInertia() { - return centimeterstothefourth.HasValue ? FromCentimetersToTheFourth(centimeterstothefourth.Value) : default(AreaMomentOfInertia?); + BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); } /// - /// Get nullable AreaMomentOfInertia from nullable DecimetersToTheFourth. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromDecimetersToTheFourth(QuantityValue? decimeterstothefourth) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public AreaMomentOfInertia(double numericValue, AreaMomentOfInertiaUnit unit) { - return decimeterstothefourth.HasValue ? FromDecimetersToTheFourth(decimeterstothefourth.Value) : default(AreaMomentOfInertia?); + if(unit == AreaMomentOfInertiaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + /// - /// Get nullable AreaMomentOfInertia from nullable FeetToTheFourth. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromFeetToTheFourth(QuantityValue? feettothefourth) + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. + /// + public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; + + /// + /// Represents the largest possible value of AreaMomentOfInertia + /// + public static AreaMomentOfInertia MaxValue => new AreaMomentOfInertia(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of AreaMomentOfInertia + /// + public static AreaMomentOfInertia MinValue => new AreaMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.AreaMomentOfInertia; + + /// + /// All units of measurement for the AreaMomentOfInertia quantity. + /// + public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. + /// + public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => AreaMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get AreaMomentOfInertia in CentimetersToTheFourth. + /// + public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in DecimetersToTheFourth. + /// + public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in FeetToTheFourth. + /// + public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); + + /// + /// Get AreaMomentOfInertia in InchesToTheFourth. + /// + public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); + + /// + /// Get AreaMomentOfInertia in MetersToTheFourth. + /// + public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); + + /// + /// Get AreaMomentOfInertia in MillimetersToTheFourth. + /// + public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) { - return feettothefourth.HasValue ? FromFeetToTheFourth(feettothefourth.Value) : default(AreaMomentOfInertia?); + return GetAbbreviation(unit, null); } /// - /// Get nullable AreaMomentOfInertia from nullable InchesToTheFourth. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromInchesToTheFourth(QuantityValue? inchestothefourth) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) { - return inchestothefourth.HasValue ? FromInchesToTheFourth(inchestothefourth.Value) : default(AreaMomentOfInertia?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable AreaMomentOfInertia from nullable MetersToTheFourth. + /// Get AreaMomentOfInertia from CentimetersToTheFourth. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromMetersToTheFourth(QuantityValue? meterstothefourth) + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) { - return meterstothefourth.HasValue ? FromMetersToTheFourth(meterstothefourth.Value) : default(AreaMomentOfInertia?); + double value = (double) centimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from DecimetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) + { + double value = (double) decimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); } - /// - /// Get nullable AreaMomentOfInertia from nullable MillimetersToTheFourth. + /// Get AreaMomentOfInertia from FeetToTheFourth. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static AreaMomentOfInertia? FromMillimetersToTheFourth(QuantityValue? millimeterstothefourth) + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) { - return millimeterstothefourth.HasValue ? FromMillimetersToTheFourth(millimeterstothefourth.Value) : default(AreaMomentOfInertia?); + double value = (double) feettothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); + } + /// + /// Get AreaMomentOfInertia from InchesToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) + { + double value = (double) inchestothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) + { + double value = (double) meterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); + } + /// + /// Get AreaMomentOfInertia from MillimetersToTheFourth. + /// + /// If value is NaN or Infinity. + public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) + { + double value = (double) millimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); } /// @@ -122,28 +267,156 @@ public partial struct AreaMomentOfInertia : IComparable, IComparableValue to convert from. /// Unit to convert from. /// AreaMomentOfInertia unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static AreaMomentOfInertia? From(QuantityValue? value, AreaMomentOfInertiaUnit fromUnit) + public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) { - return value.HasValue ? new AreaMomentOfInertia((double)value.Value, fromUnit) : default(AreaMomentOfInertia?); + return new AreaMomentOfInertia((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static AreaMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaMomentOfInertia result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static AreaMomentOfInertiaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out AreaMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static AreaMomentOfInertia operator -(AreaMomentOfInertia right) @@ -183,6 +456,8 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(AreaMomentOfInertia left, AreaMomentOfInertia right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -203,180 +478,226 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) + public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Equals(right); + } + + public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); + } + + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(AreaMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(AreaMomentOfInertia other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - AreaMomentOfInertiaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersToTheFourth(x.MetersToTheFourth + y.MetersToTheFourth)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out AreaMomentOfInertia result) + /// A hash code for the current AreaMomentOfInertia. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(AreaMomentOfInertia); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaMomentOfInertiaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A AreaMomentOfInertia with the specified unit. + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new AreaMomentOfInertia(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == AreaMomentOfInertiaUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs index d6e6e0745f..bc9a4ed598 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,249 +49,499 @@ namespace UnitsNet /// /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct BitRate : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Bit_rate + /// + public partial struct BitRate : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; - - #region Nullable From Methods + private readonly decimal _value; /// - /// Get nullable BitRate from nullable BitsPerSecond. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromBitsPerSecond(QuantityValue? bitspersecond) + private readonly BitRateUnit? _unit; + + static BitRate() { - return bitspersecond.HasValue ? FromBitsPerSecond(bitspersecond.Value) : default(BitRate?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable BitRate from nullable BytesPerSecond. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromBytesPerSecond(QuantityValue? bytespersecond) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public BitRate(decimal numericValue, BitRateUnit unit) { - return bytespersecond.HasValue ? FromBytesPerSecond(bytespersecond.Value) : default(BitRate?); + if(unit == BitRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. + /// + public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; + + /// + /// Represents the largest possible value of BitRate + /// + public static BitRate MaxValue => new BitRate(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of BitRate + /// + public static BitRate MinValue => new BitRate(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.BitRate; + + /// + /// All units of measurement for the BitRate quantity. + /// + public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. + /// + public static BitRate Zero => new BitRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public decimal Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BitRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BitRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get BitRate in BitsPerSecond. + /// + public double BitsPerSecond => As(BitRateUnit.BitPerSecond); + + /// + /// Get BitRate in BytesPerSecond. + /// + public double BytesPerSecond => As(BitRateUnit.BytePerSecond); + + /// + /// Get BitRate in ExabitsPerSecond. + /// + public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + + /// + /// Get BitRate in ExabytesPerSecond. + /// + public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + + /// + /// Get BitRate in ExbibitsPerSecond. + /// + public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + + /// + /// Get BitRate in ExbibytesPerSecond. + /// + public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + + /// + /// Get BitRate in GibibitsPerSecond. + /// + public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + + /// + /// Get BitRate in GibibytesPerSecond. + /// + public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + + /// + /// Get BitRate in GigabitsPerSecond. + /// + public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + + /// + /// Get BitRate in GigabytesPerSecond. + /// + public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + + /// + /// Get BitRate in KibibitsPerSecond. + /// + public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + + /// + /// Get BitRate in KibibytesPerSecond. + /// + public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + + /// + /// Get BitRate in KilobitsPerSecond. + /// + public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + + /// + /// Get BitRate in KilobytesPerSecond. + /// + public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + + /// + /// Get BitRate in MebibitsPerSecond. + /// + public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + + /// + /// Get BitRate in MebibytesPerSecond. + /// + public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + + /// + /// Get BitRate in MegabitsPerSecond. + /// + public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + + /// + /// Get BitRate in MegabytesPerSecond. + /// + public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + + /// + /// Get BitRate in PebibitsPerSecond. + /// + public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + + /// + /// Get BitRate in PebibytesPerSecond. + /// + public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + + /// + /// Get BitRate in PetabitsPerSecond. + /// + public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + + /// + /// Get BitRate in PetabytesPerSecond. + /// + public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + + /// + /// Get BitRate in TebibitsPerSecond. + /// + public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + /// - /// Get nullable BitRate from nullable ExabitsPerSecond. + /// Get BitRate in TebibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromExabitsPerSecond(QuantityValue? exabitspersecond) + public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + + /// + /// Get BitRate in TerabitsPerSecond. + /// + public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + + /// + /// Get BitRate in TerabytesPerSecond. + /// + public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BitRateUnit unit) { - return exabitspersecond.HasValue ? FromExabitsPerSecond(exabitspersecond.Value) : default(BitRate?); + return GetAbbreviation(unit, null); } /// - /// Get nullable BitRate from nullable ExabytesPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromExabytesPerSecond(QuantityValue? exabytespersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] IFormatProvider provider) { - return exabytespersecond.HasValue ? FromExabytesPerSecond(exabytespersecond.Value) : default(BitRate?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable BitRate from nullable ExbibitsPerSecond. + /// Get BitRate from BitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromExbibitsPerSecond(QuantityValue? exbibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) { - return exbibitspersecond.HasValue ? FromExbibitsPerSecond(exbibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); } - /// - /// Get nullable BitRate from nullable ExbibytesPerSecond. + /// Get BitRate from BytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromExbibytesPerSecond(QuantityValue? exbibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) { - return exbibytespersecond.HasValue ? FromExbibytesPerSecond(exbibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); } - /// - /// Get nullable BitRate from nullable GibibitsPerSecond. + /// Get BitRate from ExabitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromGibibitsPerSecond(QuantityValue? gibibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) { - return gibibitspersecond.HasValue ? FromGibibitsPerSecond(gibibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); } - /// - /// Get nullable BitRate from nullable GibibytesPerSecond. + /// Get BitRate from ExabytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromGibibytesPerSecond(QuantityValue? gibibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) { - return gibibytespersecond.HasValue ? FromGibibytesPerSecond(gibibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); } - /// - /// Get nullable BitRate from nullable GigabitsPerSecond. + /// Get BitRate from ExbibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromGigabitsPerSecond(QuantityValue? gigabitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) { - return gigabitspersecond.HasValue ? FromGigabitsPerSecond(gigabitspersecond.Value) : default(BitRate?); + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); } - /// - /// Get nullable BitRate from nullable GigabytesPerSecond. + /// Get BitRate from ExbibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromGigabytesPerSecond(QuantityValue? gigabytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) { - return gigabytespersecond.HasValue ? FromGigabytesPerSecond(gigabytespersecond.Value) : default(BitRate?); + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); } - /// - /// Get nullable BitRate from nullable KibibitsPerSecond. + /// Get BitRate from GibibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromKibibitsPerSecond(QuantityValue? kibibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) { - return kibibitspersecond.HasValue ? FromKibibitsPerSecond(kibibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); } - /// - /// Get nullable BitRate from nullable KibibytesPerSecond. + /// Get BitRate from GibibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromKibibytesPerSecond(QuantityValue? kibibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) { - return kibibytespersecond.HasValue ? FromKibibytesPerSecond(kibibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); } - /// - /// Get nullable BitRate from nullable KilobitsPerSecond. + /// Get BitRate from GigabitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromKilobitsPerSecond(QuantityValue? kilobitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) { - return kilobitspersecond.HasValue ? FromKilobitsPerSecond(kilobitspersecond.Value) : default(BitRate?); + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); } - /// - /// Get nullable BitRate from nullable KilobytesPerSecond. + /// Get BitRate from GigabytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromKilobytesPerSecond(QuantityValue? kilobytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) { - return kilobytespersecond.HasValue ? FromKilobytesPerSecond(kilobytespersecond.Value) : default(BitRate?); + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); } - /// - /// Get nullable BitRate from nullable MebibitsPerSecond. + /// Get BitRate from KibibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromMebibitsPerSecond(QuantityValue? mebibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) { - return mebibitspersecond.HasValue ? FromMebibitsPerSecond(mebibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); } - /// - /// Get nullable BitRate from nullable MebibytesPerSecond. + /// Get BitRate from KibibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromMebibytesPerSecond(QuantityValue? mebibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) { - return mebibytespersecond.HasValue ? FromMebibytesPerSecond(mebibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); } - /// - /// Get nullable BitRate from nullable MegabitsPerSecond. + /// Get BitRate from KilobitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromMegabitsPerSecond(QuantityValue? megabitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) { - return megabitspersecond.HasValue ? FromMegabitsPerSecond(megabitspersecond.Value) : default(BitRate?); + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); } - /// - /// Get nullable BitRate from nullable MegabytesPerSecond. + /// Get BitRate from KilobytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromMegabytesPerSecond(QuantityValue? megabytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) { - return megabytespersecond.HasValue ? FromMegabytesPerSecond(megabytespersecond.Value) : default(BitRate?); + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); } - /// - /// Get nullable BitRate from nullable PebibitsPerSecond. + /// Get BitRate from MebibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromPebibitsPerSecond(QuantityValue? pebibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) { - return pebibitspersecond.HasValue ? FromPebibitsPerSecond(pebibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); } - /// - /// Get nullable BitRate from nullable PebibytesPerSecond. + /// Get BitRate from MebibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromPebibytesPerSecond(QuantityValue? pebibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) { - return pebibytespersecond.HasValue ? FromPebibytesPerSecond(pebibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); } - /// - /// Get nullable BitRate from nullable PetabitsPerSecond. + /// Get BitRate from MegabitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromPetabitsPerSecond(QuantityValue? petabitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) { - return petabitspersecond.HasValue ? FromPetabitsPerSecond(petabitspersecond.Value) : default(BitRate?); + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); } - /// - /// Get nullable BitRate from nullable PetabytesPerSecond. + /// Get BitRate from MegabytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromPetabytesPerSecond(QuantityValue? petabytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) { - return petabytespersecond.HasValue ? FromPetabytesPerSecond(petabytespersecond.Value) : default(BitRate?); + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); } - /// - /// Get nullable BitRate from nullable TebibitsPerSecond. + /// Get BitRate from PebibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromTebibitsPerSecond(QuantityValue? tebibitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) { - return tebibitspersecond.HasValue ? FromTebibitsPerSecond(tebibitspersecond.Value) : default(BitRate?); + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); } - /// - /// Get nullable BitRate from nullable TebibytesPerSecond. + /// Get BitRate from PebibytesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromTebibytesPerSecond(QuantityValue? tebibytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) { - return tebibytespersecond.HasValue ? FromTebibytesPerSecond(tebibytespersecond.Value) : default(BitRate?); + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); } - /// - /// Get nullable BitRate from nullable TerabitsPerSecond. + /// Get BitRate from PetabitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromTerabitsPerSecond(QuantityValue? terabitspersecond) + /// If value is NaN or Infinity. + public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) { - return terabitspersecond.HasValue ? FromTerabitsPerSecond(terabitspersecond.Value) : default(BitRate?); + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); + } + /// + /// Get BitRate from PetabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) + { + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); } - /// - /// Get nullable BitRate from nullable TerabytesPerSecond. + /// Get BitRate from TebibitsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BitRate? FromTerabytesPerSecond(QuantityValue? terabytespersecond) + /// If value is NaN or Infinity. + public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) { - return terabytespersecond.HasValue ? FromTerabytesPerSecond(terabytespersecond.Value) : default(BitRate?); + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); + } + /// + /// Get BitRate from TebibytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) + { + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); + } + /// + /// Get BitRate from TerabitsPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) + { + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); + } + /// + /// Get BitRate from TerabytesPerSecond. + /// + /// If value is NaN or Infinity. + public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) + { + decimal value = (decimal) terabytespersecond; + return new BitRate(value, BitRateUnit.TerabytePerSecond); } /// @@ -302,28 +550,156 @@ public partial struct BitRate : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// BitRate unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BitRate? From(QuantityValue? value, BitRateUnit fromUnit) + public static BitRate From(QuantityValue value, BitRateUnit fromUnit) { - return value.HasValue ? new BitRate((decimal)value.Value, fromUnit) : default(BitRate?); + return new BitRate((decimal)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static BitRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BitRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BitRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static BitRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static BitRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BitRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out BitRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static BitRate operator -(BitRate right) @@ -363,6 +739,8 @@ public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] IFormatProvid #endregion + #region Equality / IComparable + public static bool operator <=(BitRate left, BitRate right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -383,178 +761,266 @@ public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] IFormatProvid return left.Value > right.AsBaseNumericType(left.Unit); } - public static bool operator ==(BitRate left, BitRate right) + public static bool operator ==(BitRate left, BitRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - public static bool operator !=(BitRate left, BitRate right) + public static bool operator !=(BitRate left, BitRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(BitRate other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BitRate Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - BitRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromBitsPerSecond(x.BitsPerSecond + y.BitsPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BitRate result) + /// A hash code for the current BitRate. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(BitRate); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BitRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this BitRate to another BitRate with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A BitRate with the specified unit. + public BitRate ToUnit(BitRateUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new BitRate(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BitRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private decimal AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == BitRateUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BitRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(BitRateUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs index 9633d92282..24001bf446 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct BrakeSpecificFuelConsumption : IComparable, IComparable + public partial struct BrakeSpecificFuelConsumption : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + static BrakeSpecificFuelConsumption() + { + BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public BrakeSpecificFuelConsumption(double numericValue, BrakeSpecificFuelConsumptionUnit unit) + { + if(unit == BrakeSpecificFuelConsumptionUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. + /// + public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + + /// + /// Represents the largest possible value of BrakeSpecificFuelConsumption + /// + public static BrakeSpecificFuelConsumption MaxValue => new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of BrakeSpecificFuelConsumption + /// + public static BrakeSpecificFuelConsumption MinValue => new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.BrakeSpecificFuelConsumption; + + /// + /// All units of measurement for the BrakeSpecificFuelConsumption quantity. + /// + public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. + /// + public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable BrakeSpecificFuelConsumption from nullable GramsPerKiloWattHour. + /// Get BrakeSpecificFuelConsumption in GramsPerKiloWattHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? FromGramsPerKiloWattHour(QuantityValue? gramsperkilowatthour) + public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + + /// + /// Get BrakeSpecificFuelConsumption in KilogramsPerJoule. + /// + public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + + /// + /// Get BrakeSpecificFuelConsumption in PoundsPerMechanicalHorsepowerHour. + /// + public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) { - return gramsperkilowatthour.HasValue ? FromGramsPerKiloWattHour(gramsperkilowatthour.Value) : default(BrakeSpecificFuelConsumption?); + return GetAbbreviation(unit, null); } /// - /// Get nullable BrakeSpecificFuelConsumption from nullable KilogramsPerJoule. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? FromKilogramsPerJoule(QuantityValue? kilogramsperjoule) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider) { - return kilogramsperjoule.HasValue ? FromKilogramsPerJoule(kilogramsperjoule.Value) : default(BrakeSpecificFuelConsumption?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. + /// + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) + { + double value = (double) gramsperkilowatthour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + } /// - /// Get nullable BrakeSpecificFuelConsumption from nullable PoundsPerMechanicalHorsepowerHour. + /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? FromPoundsPerMechanicalHorsepowerHour(QuantityValue? poundspermechanicalhorsepowerhour) + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) { - return poundspermechanicalhorsepowerhour.HasValue ? FromPoundsPerMechanicalHorsepowerHour(poundspermechanicalhorsepowerhour.Value) : default(BrakeSpecificFuelConsumption?); + double value = (double) kilogramsperjoule; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + } + /// + /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. + /// + /// If value is NaN or Infinity. + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) + { + double value = (double) poundspermechanicalhorsepowerhour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); } /// @@ -95,28 +225,156 @@ public partial struct BrakeSpecificFuelConsumption : IComparable, IComparable
Value to convert from. /// Unit to convert from. /// BrakeSpecificFuelConsumption unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static BrakeSpecificFuelConsumption? From(QuantityValue? value, BrakeSpecificFuelConsumptionUnit fromUnit) + public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) { - return value.HasValue ? new BrakeSpecificFuelConsumption((double)value.Value, fromUnit) : default(BrakeSpecificFuelConsumption?); + return new BrakeSpecificFuelConsumption((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BrakeSpecificFuelConsumption result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out BrakeSpecificFuelConsumptionUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [Can #endregion + #region Equality / IComparable + public static bool operator <=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [Can return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(BrakeSpecificFuelConsumption, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(BrakeSpecificFuelConsumption, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(BrakeSpecificFuelConsumption other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - BrakeSpecificFuelConsumptionUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerJoule(x.KilogramsPerJoule + y.KilogramsPerJoule)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out BrakeSpecificFuelConsumption result) + /// A hash code for the current BrakeSpecificFuelConsumption. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(BrakeSpecificFuelConsumption); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BrakeSpecificFuelConsumptionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A BrakeSpecificFuelConsumption with the specified unit. + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new BrakeSpecificFuelConsumption(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BrakeSpecificFuelConsumptionUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs index 346f5a74fd..5c1005d203 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,205 @@ namespace UnitsNet /// /// Capacitance is the ability of a body to store an electric charge. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Capacitance : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Capacitance + /// + public partial struct Capacitance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Capacitance from nullable Farads. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Capacitance? FromFarads(QuantityValue? farads) + private readonly CapacitanceUnit? _unit; + + static Capacitance() { - return farads.HasValue ? FromFarads(farads.Value) : default(Capacitance?); + BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); } /// - /// Get nullable Capacitance from nullable Microfarads. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Capacitance? FromMicrofarads(QuantityValue? microfarads) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Capacitance(double numericValue, CapacitanceUnit unit) { - return microfarads.HasValue ? FromMicrofarads(microfarads.Value) : default(Capacitance?); + if(unit == CapacitanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Capacitance, which is Farad. All conversions go via this value. + /// + public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; + + /// + /// Represents the largest possible value of Capacitance + /// + public static Capacitance MaxValue => new Capacitance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Capacitance + /// + public static Capacitance MinValue => new Capacitance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Capacitance; + + /// + /// All units of measurement for the Capacitance quantity. + /// + public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Farad. + /// + public static Capacitance Zero => new Capacitance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Capacitance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Capacitance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Capacitance in Farads. + /// + public double Farads => As(CapacitanceUnit.Farad); + + /// + /// Get Capacitance in Microfarads. + /// + public double Microfarads => As(CapacitanceUnit.Microfarad); + + /// + /// Get Capacitance in Millifarads. + /// + public double Millifarads => As(CapacitanceUnit.Millifarad); + + /// + /// Get Capacitance in Nanofarads. + /// + public double Nanofarads => As(CapacitanceUnit.Nanofarad); + + /// + /// Get Capacitance in Picofarads. + /// + public double Picofarads => As(CapacitanceUnit.Picofarad); + + #endregion + + #region Static Methods + /// - /// Get nullable Capacitance from nullable Millifarads. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Capacitance? FromMillifarads(QuantityValue? millifarads) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CapacitanceUnit unit) { - return millifarads.HasValue ? FromMillifarads(millifarads.Value) : default(Capacitance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Capacitance from nullable Nanofarads. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Capacitance? FromNanofarads(QuantityValue? nanofarads) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider) { - return nanofarads.HasValue ? FromNanofarads(nanofarads.Value) : default(Capacitance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get Capacitance from Farads. + /// + /// If value is NaN or Infinity. + public static Capacitance FromFarads(QuantityValue farads) + { + double value = (double) farads; + return new Capacitance(value, CapacitanceUnit.Farad); + } + /// + /// Get Capacitance from Microfarads. + /// + /// If value is NaN or Infinity. + public static Capacitance FromMicrofarads(QuantityValue microfarads) + { + double value = (double) microfarads; + return new Capacitance(value, CapacitanceUnit.Microfarad); + } + /// + /// Get Capacitance from Millifarads. + /// + /// If value is NaN or Infinity. + public static Capacitance FromMillifarads(QuantityValue millifarads) + { + double value = (double) millifarads; + return new Capacitance(value, CapacitanceUnit.Millifarad); + } + /// + /// Get Capacitance from Nanofarads. + /// + /// If value is NaN or Infinity. + public static Capacitance FromNanofarads(QuantityValue nanofarads) + { + double value = (double) nanofarads; + return new Capacitance(value, CapacitanceUnit.Nanofarad); + } /// - /// Get nullable Capacitance from nullable Picofarads. + /// Get Capacitance from Picofarads. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Capacitance? FromPicofarads(QuantityValue? picofarads) + /// If value is NaN or Infinity. + public static Capacitance FromPicofarads(QuantityValue picofarads) { - return picofarads.HasValue ? FromPicofarads(picofarads.Value) : default(Capacitance?); + double value = (double) picofarads; + return new Capacitance(value, CapacitanceUnit.Picofarad); } /// @@ -113,28 +256,156 @@ public partial struct Capacitance : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Capacitance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Capacitance? From(QuantityValue? value, CapacitanceUnit fromUnit) + public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) { - return value.HasValue ? new Capacitance((double)value.Value, fromUnit) : default(Capacitance?); + return new Capacitance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Capacitance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Capacitance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Capacitance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static CapacitanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static CapacitanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CapacitanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out CapacitanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Capacitance operator -(Capacitance right) @@ -174,6 +445,8 @@ public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(Capacitance left, Capacitance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +467,224 @@ public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Capacitance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Capacitance left, Capacitance right) + public static bool operator ==(Capacitance left, Capacitance right) + { + return left.Equals(right); + } + + public static bool operator !=(Capacitance left, Capacitance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Capacitance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Capacitance left, Capacitance right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Capacitance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Capacitance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Capacitance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - CapacitanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromFarads(x.Farads + y.Farads)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Capacitance result) + /// A hash code for the current Capacitance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Capacitance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CapacitanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Capacitance to another Capacitance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Capacitance with the specified unit. + public Capacitance ToUnit(CapacitanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Capacitance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CapacitanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case CapacitanceUnit.Farad: return _value; + 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == CapacitanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CapacitanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case CapacitanceUnit.Farad: return baseUnitValue; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs index 2bc5a60d1e..f0f973ddc0 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// A unit that represents a fractional change in size in response to a change in temperature. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct CoefficientOfThermalExpansion : IComparable, IComparable + public partial struct CoefficientOfThermalExpansion : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CoefficientOfThermalExpansionUnit? _unit; + + static CoefficientOfThermalExpansion() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public CoefficientOfThermalExpansion(double numericValue, CoefficientOfThermalExpansionUnit unit) + { + if(unit == CoefficientOfThermalExpansionUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. + /// + public static CoefficientOfThermalExpansionUnit BaseUnit => CoefficientOfThermalExpansionUnit.InverseKelvin; + + /// + /// Represents the largest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MaxValue => new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of CoefficientOfThermalExpansion + /// + public static CoefficientOfThermalExpansion MinValue => new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.CoefficientOfThermalExpansion; + + /// + /// All units of measurement for the CoefficientOfThermalExpansion quantity. + /// + public static CoefficientOfThermalExpansionUnit[] Units { get; } = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. + /// + public static CoefficientOfThermalExpansion Zero => new CoefficientOfThermalExpansion(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable CoefficientOfThermalExpansion from nullable InverseDegreeCelsius. + /// Get CoefficientOfThermalExpansion in InverseDegreeCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? FromInverseDegreeCelsius(QuantityValue? inversedegreecelsius) + public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + + /// + /// Get CoefficientOfThermalExpansion in InverseDegreeFahrenheit. + /// + public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + + /// + /// Get CoefficientOfThermalExpansion in InverseKelvin. + /// + public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) { - return inversedegreecelsius.HasValue ? FromInverseDegreeCelsius(inversedegreecelsius.Value) : default(CoefficientOfThermalExpansion?); + return GetAbbreviation(unit, null); } /// - /// Get nullable CoefficientOfThermalExpansion from nullable InverseDegreeFahrenheit. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? FromInverseDegreeFahrenheit(QuantityValue? inversedegreefahrenheit) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider) { - return inversedegreefahrenheit.HasValue ? FromInverseDegreeFahrenheit(inversedegreefahrenheit.Value) : default(CoefficientOfThermalExpansion?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get CoefficientOfThermalExpansion from InverseDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius) + { + double value = (double) inversedegreecelsius; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + } /// - /// Get nullable CoefficientOfThermalExpansion from nullable InverseKelvin. + /// Get CoefficientOfThermalExpansion from InverseDegreeFahrenheit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? FromInverseKelvin(QuantityValue? inversekelvin) + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit) { - return inversekelvin.HasValue ? FromInverseKelvin(inversekelvin.Value) : default(CoefficientOfThermalExpansion?); + double value = (double) inversedegreefahrenheit; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + } + /// + /// Get CoefficientOfThermalExpansion from InverseKelvin. + /// + /// If value is NaN or Infinity. + public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin) + { + double value = (double) inversekelvin; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); } /// @@ -95,28 +225,156 @@ public partial struct CoefficientOfThermalExpansion : IComparable, IComparableValue to convert from. /// Unit to convert from. /// CoefficientOfThermalExpansion unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static CoefficientOfThermalExpansion? From(QuantityValue? value, CoefficientOfThermalExpansionUnit fromUnit) + public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) { - return value.HasValue ? new CoefficientOfThermalExpansion((double)value.Value, fromUnit) : default(CoefficientOfThermalExpansion?); + return new CoefficientOfThermalExpansion((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static CoefficientOfThermalExpansion Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out CoefficientOfThermalExpansion result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out CoefficientOfThermalExpansion result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static CoefficientOfThermalExpansionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out CoefficientOfThermalExpansionUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [Ca #endregion + #region Equality / IComparable + public static bool operator <=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [Ca return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(CoefficientOfThermalExpansion, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(CoefficientOfThermalExpansion, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(CoefficientOfThermalExpansion other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static CoefficientOfThermalExpansion Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(CoefficientOfThermalExpansion other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - CoefficientOfThermalExpansionUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromInverseKelvin(x.InverseKelvin + y.InverseKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out CoefficientOfThermalExpansion result) + /// A hash code for the current CoefficientOfThermalExpansion. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(CoefficientOfThermalExpansion); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CoefficientOfThermalExpansionUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static CoefficientOfThermalExpansionUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A CoefficientOfThermalExpansion with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new CoefficientOfThermalExpansion(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value*5/9; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == CoefficientOfThermalExpansionUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CoefficientOfThermalExpansionUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; + case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue*9/5; + case CoefficientOfThermalExpansionUnit.InverseKelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(CoefficientOfThermalExpansionUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs index 9e9043fc0d..a1bc4cec77 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,357 +49,667 @@ namespace UnitsNet /// /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Density : IComparable, IComparable + /// + /// http://en.wikipedia.org/wiki/Density + /// + public partial struct Density : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Density from nullable CentigramsPerDeciLiter. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromCentigramsPerDeciLiter(QuantityValue? centigramsperdeciliter) + private readonly DensityUnit? _unit; + + static Density() { - return centigramsperdeciliter.HasValue ? FromCentigramsPerDeciLiter(centigramsperdeciliter.Value) : default(Density?); + BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); } /// - /// Get nullable Density from nullable CentigramsPerLiter. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromCentigramsPerLiter(QuantityValue? centigramsperliter) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Density(double numericValue, DensityUnit unit) { - return centigramsperliter.HasValue ? FromCentigramsPerLiter(centigramsperliter.Value) : default(Density?); + if(unit == DensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. + /// + public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; + + /// + /// Represents the largest possible value of Density + /// + public static Density MaxValue => new Density(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Density + /// + public static Density MinValue => new Density(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Density; + + /// + /// All units of measurement for the Density quantity. + /// + public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// + public static Density Zero => new Density(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Density.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Density.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Density in CentigramsPerDeciLiter. + /// + public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); + + /// + /// Get Density in CentigramsPerLiter. + /// + public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); + + /// + /// Get Density in CentigramsPerMilliliter. + /// + public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); + + /// + /// Get Density in DecigramsPerDeciLiter. + /// + public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); + + /// + /// Get Density in DecigramsPerLiter. + /// + public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); + + /// + /// Get Density in DecigramsPerMilliliter. + /// + public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); + + /// + /// Get Density in GramsPerCubicCentimeter. + /// + public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); + + /// + /// Get Density in GramsPerCubicMeter. + /// + public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); + + /// + /// Get Density in GramsPerCubicMillimeter. + /// + public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); + + /// + /// Get Density in GramsPerDeciLiter. + /// + public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); + + /// + /// Get Density in GramsPerLiter. + /// + public double GramsPerLiter => As(DensityUnit.GramPerLiter); + + /// + /// Get Density in GramsPerMilliliter. + /// + public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); + + /// + /// Get Density in KilogramsPerCubicCentimeter. + /// + public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); + + /// + /// Get Density in KilogramsPerCubicMeter. + /// + public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); + + /// + /// Get Density in KilogramsPerCubicMillimeter. + /// + public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); + + /// + /// Get Density in KilopoundsPerCubicFoot. + /// + public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); + + /// + /// Get Density in KilopoundsPerCubicInch. + /// + public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); + + /// + /// Get Density in MicrogramsPerDeciLiter. + /// + public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); + + /// + /// Get Density in MicrogramsPerLiter. + /// + public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); + + /// + /// Get Density in MicrogramsPerMilliliter. + /// + public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); + + /// + /// Get Density in MilligramsPerCubicMeter. + /// + public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); + + /// + /// Get Density in MilligramsPerDeciLiter. + /// + public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); + + /// + /// Get Density in MilligramsPerLiter. + /// + public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); + + /// + /// Get Density in MilligramsPerMilliliter. + /// + public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); + + /// + /// Get Density in NanogramsPerDeciLiter. + /// + public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); + + /// + /// Get Density in NanogramsPerLiter. + /// + public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); + + /// + /// Get Density in NanogramsPerMilliliter. + /// + public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); + + /// + /// Get Density in PicogramsPerDeciLiter. + /// + public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); + + /// + /// Get Density in PicogramsPerLiter. + /// + public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); + + /// + /// Get Density in PicogramsPerMilliliter. + /// + public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); + + /// + /// Get Density in PoundsPerCubicFoot. + /// + public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); + + /// + /// Get Density in PoundsPerCubicInch. + /// + public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); + + /// + /// Get Density in PoundsPerImperialGallon. + /// + public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); + + /// + /// Get Density in PoundsPerUSGallon. + /// + public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); + + /// + /// Get Density in SlugsPerCubicFoot. + /// + public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); + + /// + /// Get Density in TonnesPerCubicCentimeter. + /// + public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); + + /// + /// Get Density in TonnesPerCubicMeter. + /// + public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); + /// - /// Get nullable Density from nullable CentigramsPerMilliliter. + /// Get Density in TonnesPerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromCentigramsPerMilliliter(QuantityValue? centigramspermilliliter) + public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DensityUnit unit) { - return centigramspermilliliter.HasValue ? FromCentigramsPerMilliliter(centigramspermilliliter.Value) : default(Density?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Density from nullable DecigramsPerDeciLiter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromDecigramsPerDeciLiter(QuantityValue? decigramsperdeciliter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(DensityUnit unit, [CanBeNull] IFormatProvider provider) { - return decigramsperdeciliter.HasValue ? FromDecigramsPerDeciLiter(decigramsperdeciliter.Value) : default(Density?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Density from nullable DecigramsPerLiter. + /// Get Density from CentigramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromDecigramsPerLiter(QuantityValue? decigramsperliter) + /// If value is NaN or Infinity. + public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) { - return decigramsperliter.HasValue ? FromDecigramsPerLiter(decigramsperliter.Value) : default(Density?); + double value = (double) centigramsperdeciliter; + return new Density(value, DensityUnit.CentigramPerDeciliter); } - /// - /// Get nullable Density from nullable DecigramsPerMilliliter. + /// Get Density from CentigramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromDecigramsPerMilliliter(QuantityValue? decigramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) { - return decigramspermilliliter.HasValue ? FromDecigramsPerMilliliter(decigramspermilliliter.Value) : default(Density?); + double value = (double) centigramsperliter; + return new Density(value, DensityUnit.CentigramPerLiter); } - /// - /// Get nullable Density from nullable GramsPerCubicCentimeter. + /// Get Density from CentigramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerCubicCentimeter(QuantityValue? gramspercubiccentimeter) + /// If value is NaN or Infinity. + public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) { - return gramspercubiccentimeter.HasValue ? FromGramsPerCubicCentimeter(gramspercubiccentimeter.Value) : default(Density?); + double value = (double) centigramspermilliliter; + return new Density(value, DensityUnit.CentigramPerMilliliter); } - /// - /// Get nullable Density from nullable GramsPerCubicMeter. + /// Get Density from DecigramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerCubicMeter(QuantityValue? gramspercubicmeter) + /// If value is NaN or Infinity. + public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) { - return gramspercubicmeter.HasValue ? FromGramsPerCubicMeter(gramspercubicmeter.Value) : default(Density?); + double value = (double) decigramsperdeciliter; + return new Density(value, DensityUnit.DecigramPerDeciliter); } - /// - /// Get nullable Density from nullable GramsPerCubicMillimeter. + /// Get Density from DecigramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerCubicMillimeter(QuantityValue? gramspercubicmillimeter) + /// If value is NaN or Infinity. + public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) { - return gramspercubicmillimeter.HasValue ? FromGramsPerCubicMillimeter(gramspercubicmillimeter.Value) : default(Density?); + double value = (double) decigramsperliter; + return new Density(value, DensityUnit.DecigramPerLiter); } - /// - /// Get nullable Density from nullable GramsPerDeciLiter. + /// Get Density from DecigramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerDeciLiter(QuantityValue? gramsperdeciliter) + /// If value is NaN or Infinity. + public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) { - return gramsperdeciliter.HasValue ? FromGramsPerDeciLiter(gramsperdeciliter.Value) : default(Density?); + double value = (double) decigramspermilliliter; + return new Density(value, DensityUnit.DecigramPerMilliliter); } - /// - /// Get nullable Density from nullable GramsPerLiter. + /// Get Density from GramsPerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerLiter(QuantityValue? gramsperliter) + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) { - return gramsperliter.HasValue ? FromGramsPerLiter(gramsperliter.Value) : default(Density?); + double value = (double) gramspercubiccentimeter; + return new Density(value, DensityUnit.GramPerCubicCentimeter); } - /// - /// Get nullable Density from nullable GramsPerMilliliter. + /// Get Density from GramsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromGramsPerMilliliter(QuantityValue? gramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) { - return gramspermilliliter.HasValue ? FromGramsPerMilliliter(gramspermilliliter.Value) : default(Density?); + double value = (double) gramspercubicmeter; + return new Density(value, DensityUnit.GramPerCubicMeter); } - /// - /// Get nullable Density from nullable KilogramsPerCubicCentimeter. + /// Get Density from GramsPerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromKilogramsPerCubicCentimeter(QuantityValue? kilogramspercubiccentimeter) + /// If value is NaN or Infinity. + public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) { - return kilogramspercubiccentimeter.HasValue ? FromKilogramsPerCubicCentimeter(kilogramspercubiccentimeter.Value) : default(Density?); + double value = (double) gramspercubicmillimeter; + return new Density(value, DensityUnit.GramPerCubicMillimeter); } - /// - /// Get nullable Density from nullable KilogramsPerCubicMeter. + /// Get Density from GramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromKilogramsPerCubicMeter(QuantityValue? kilogramspercubicmeter) + /// If value is NaN or Infinity. + public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) { - return kilogramspercubicmeter.HasValue ? FromKilogramsPerCubicMeter(kilogramspercubicmeter.Value) : default(Density?); + double value = (double) gramsperdeciliter; + return new Density(value, DensityUnit.GramPerDeciliter); } - /// - /// Get nullable Density from nullable KilogramsPerCubicMillimeter. + /// Get Density from GramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromKilogramsPerCubicMillimeter(QuantityValue? kilogramspercubicmillimeter) + /// If value is NaN or Infinity. + public static Density FromGramsPerLiter(QuantityValue gramsperliter) { - return kilogramspercubicmillimeter.HasValue ? FromKilogramsPerCubicMillimeter(kilogramspercubicmillimeter.Value) : default(Density?); + double value = (double) gramsperliter; + return new Density(value, DensityUnit.GramPerLiter); } - /// - /// Get nullable Density from nullable KilopoundsPerCubicFoot. + /// Get Density from GramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromKilopoundsPerCubicFoot(QuantityValue? kilopoundspercubicfoot) + /// If value is NaN or Infinity. + public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) { - return kilopoundspercubicfoot.HasValue ? FromKilopoundsPerCubicFoot(kilopoundspercubicfoot.Value) : default(Density?); + double value = (double) gramspermilliliter; + return new Density(value, DensityUnit.GramPerMilliliter); } - /// - /// Get nullable Density from nullable KilopoundsPerCubicInch. + /// Get Density from KilogramsPerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromKilopoundsPerCubicInch(QuantityValue? kilopoundspercubicinch) + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) { - return kilopoundspercubicinch.HasValue ? FromKilopoundsPerCubicInch(kilopoundspercubicinch.Value) : default(Density?); + double value = (double) kilogramspercubiccentimeter; + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); } - /// - /// Get nullable Density from nullable MicrogramsPerDeciLiter. + /// Get Density from KilogramsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMicrogramsPerDeciLiter(QuantityValue? microgramsperdeciliter) + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) { - return microgramsperdeciliter.HasValue ? FromMicrogramsPerDeciLiter(microgramsperdeciliter.Value) : default(Density?); + double value = (double) kilogramspercubicmeter; + return new Density(value, DensityUnit.KilogramPerCubicMeter); } - /// - /// Get nullable Density from nullable MicrogramsPerLiter. + /// Get Density from KilogramsPerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMicrogramsPerLiter(QuantityValue? microgramsperliter) + /// If value is NaN or Infinity. + public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) { - return microgramsperliter.HasValue ? FromMicrogramsPerLiter(microgramsperliter.Value) : default(Density?); + double value = (double) kilogramspercubicmillimeter; + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); } - /// - /// Get nullable Density from nullable MicrogramsPerMilliliter. + /// Get Density from KilopoundsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMicrogramsPerMilliliter(QuantityValue? microgramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) { - return microgramspermilliliter.HasValue ? FromMicrogramsPerMilliliter(microgramspermilliliter.Value) : default(Density?); + double value = (double) kilopoundspercubicfoot; + return new Density(value, DensityUnit.KilopoundPerCubicFoot); } - /// - /// Get nullable Density from nullable MilligramsPerCubicMeter. + /// Get Density from KilopoundsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMilligramsPerCubicMeter(QuantityValue? milligramspercubicmeter) + /// If value is NaN or Infinity. + public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) { - return milligramspercubicmeter.HasValue ? FromMilligramsPerCubicMeter(milligramspercubicmeter.Value) : default(Density?); + double value = (double) kilopoundspercubicinch; + return new Density(value, DensityUnit.KilopoundPerCubicInch); } - /// - /// Get nullable Density from nullable MilligramsPerDeciLiter. + /// Get Density from MicrogramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMilligramsPerDeciLiter(QuantityValue? milligramsperdeciliter) + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) { - return milligramsperdeciliter.HasValue ? FromMilligramsPerDeciLiter(milligramsperdeciliter.Value) : default(Density?); + double value = (double) microgramsperdeciliter; + return new Density(value, DensityUnit.MicrogramPerDeciliter); } - /// - /// Get nullable Density from nullable MilligramsPerLiter. + /// Get Density from MicrogramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMilligramsPerLiter(QuantityValue? milligramsperliter) + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) { - return milligramsperliter.HasValue ? FromMilligramsPerLiter(milligramsperliter.Value) : default(Density?); + double value = (double) microgramsperliter; + return new Density(value, DensityUnit.MicrogramPerLiter); } - /// - /// Get nullable Density from nullable MilligramsPerMilliliter. + /// Get Density from MicrogramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromMilligramsPerMilliliter(QuantityValue? milligramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) { - return milligramspermilliliter.HasValue ? FromMilligramsPerMilliliter(milligramspermilliliter.Value) : default(Density?); + double value = (double) microgramspermilliliter; + return new Density(value, DensityUnit.MicrogramPerMilliliter); } - /// - /// Get nullable Density from nullable NanogramsPerDeciLiter. + /// Get Density from MilligramsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromNanogramsPerDeciLiter(QuantityValue? nanogramsperdeciliter) + /// If value is NaN or Infinity. + public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) { - return nanogramsperdeciliter.HasValue ? FromNanogramsPerDeciLiter(nanogramsperdeciliter.Value) : default(Density?); + double value = (double) milligramspercubicmeter; + return new Density(value, DensityUnit.MilligramPerCubicMeter); } - /// - /// Get nullable Density from nullable NanogramsPerLiter. + /// Get Density from MilligramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromNanogramsPerLiter(QuantityValue? nanogramsperliter) + /// If value is NaN or Infinity. + public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) { - return nanogramsperliter.HasValue ? FromNanogramsPerLiter(nanogramsperliter.Value) : default(Density?); + double value = (double) milligramsperdeciliter; + return new Density(value, DensityUnit.MilligramPerDeciliter); } - /// - /// Get nullable Density from nullable NanogramsPerMilliliter. + /// Get Density from MilligramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromNanogramsPerMilliliter(QuantityValue? nanogramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) { - return nanogramspermilliliter.HasValue ? FromNanogramsPerMilliliter(nanogramspermilliliter.Value) : default(Density?); + double value = (double) milligramsperliter; + return new Density(value, DensityUnit.MilligramPerLiter); } - /// - /// Get nullable Density from nullable PicogramsPerDeciLiter. + /// Get Density from MilligramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPicogramsPerDeciLiter(QuantityValue? picogramsperdeciliter) + /// If value is NaN or Infinity. + public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) { - return picogramsperdeciliter.HasValue ? FromPicogramsPerDeciLiter(picogramsperdeciliter.Value) : default(Density?); + double value = (double) milligramspermilliliter; + return new Density(value, DensityUnit.MilligramPerMilliliter); } - /// - /// Get nullable Density from nullable PicogramsPerLiter. + /// Get Density from NanogramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPicogramsPerLiter(QuantityValue? picogramsperliter) + /// If value is NaN or Infinity. + public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) { - return picogramsperliter.HasValue ? FromPicogramsPerLiter(picogramsperliter.Value) : default(Density?); + double value = (double) nanogramsperdeciliter; + return new Density(value, DensityUnit.NanogramPerDeciliter); } - /// - /// Get nullable Density from nullable PicogramsPerMilliliter. + /// Get Density from NanogramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPicogramsPerMilliliter(QuantityValue? picogramspermilliliter) + /// If value is NaN or Infinity. + public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) { - return picogramspermilliliter.HasValue ? FromPicogramsPerMilliliter(picogramspermilliliter.Value) : default(Density?); + double value = (double) nanogramsperliter; + return new Density(value, DensityUnit.NanogramPerLiter); } - /// - /// Get nullable Density from nullable PoundsPerCubicFoot. + /// Get Density from NanogramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPoundsPerCubicFoot(QuantityValue? poundspercubicfoot) + /// If value is NaN or Infinity. + public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) { - return poundspercubicfoot.HasValue ? FromPoundsPerCubicFoot(poundspercubicfoot.Value) : default(Density?); + double value = (double) nanogramspermilliliter; + return new Density(value, DensityUnit.NanogramPerMilliliter); } - /// - /// Get nullable Density from nullable PoundsPerCubicInch. + /// Get Density from PicogramsPerDeciLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPoundsPerCubicInch(QuantityValue? poundspercubicinch) + /// If value is NaN or Infinity. + public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) { - return poundspercubicinch.HasValue ? FromPoundsPerCubicInch(poundspercubicinch.Value) : default(Density?); + double value = (double) picogramsperdeciliter; + return new Density(value, DensityUnit.PicogramPerDeciliter); } - /// - /// Get nullable Density from nullable PoundsPerImperialGallon. + /// Get Density from PicogramsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPoundsPerImperialGallon(QuantityValue? poundsperimperialgallon) + /// If value is NaN or Infinity. + public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) { - return poundsperimperialgallon.HasValue ? FromPoundsPerImperialGallon(poundsperimperialgallon.Value) : default(Density?); + double value = (double) picogramsperliter; + return new Density(value, DensityUnit.PicogramPerLiter); } - /// - /// Get nullable Density from nullable PoundsPerUSGallon. + /// Get Density from PicogramsPerMilliliter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromPoundsPerUSGallon(QuantityValue? poundsperusgallon) + /// If value is NaN or Infinity. + public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) { - return poundsperusgallon.HasValue ? FromPoundsPerUSGallon(poundsperusgallon.Value) : default(Density?); + double value = (double) picogramspermilliliter; + return new Density(value, DensityUnit.PicogramPerMilliliter); } - /// - /// Get nullable Density from nullable SlugsPerCubicFoot. + /// Get Density from PoundsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromSlugsPerCubicFoot(QuantityValue? slugspercubicfoot) + /// If value is NaN or Infinity. + public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) { - return slugspercubicfoot.HasValue ? FromSlugsPerCubicFoot(slugspercubicfoot.Value) : default(Density?); + double value = (double) poundspercubicfoot; + return new Density(value, DensityUnit.PoundPerCubicFoot); } - /// - /// Get nullable Density from nullable TonnesPerCubicCentimeter. + /// Get Density from PoundsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromTonnesPerCubicCentimeter(QuantityValue? tonnespercubiccentimeter) + /// If value is NaN or Infinity. + public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) { - return tonnespercubiccentimeter.HasValue ? FromTonnesPerCubicCentimeter(tonnespercubiccentimeter.Value) : default(Density?); + double value = (double) poundspercubicinch; + return new Density(value, DensityUnit.PoundPerCubicInch); } - /// - /// Get nullable Density from nullable TonnesPerCubicMeter. + /// Get Density from PoundsPerImperialGallon. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromTonnesPerCubicMeter(QuantityValue? tonnespercubicmeter) + /// If value is NaN or Infinity. + public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) { - return tonnespercubicmeter.HasValue ? FromTonnesPerCubicMeter(tonnespercubicmeter.Value) : default(Density?); + double value = (double) poundsperimperialgallon; + return new Density(value, DensityUnit.PoundPerImperialGallon); } - /// - /// Get nullable Density from nullable TonnesPerCubicMillimeter. + /// Get Density from PoundsPerUSGallon. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Density? FromTonnesPerCubicMillimeter(QuantityValue? tonnespercubicmillimeter) + /// If value is NaN or Infinity. + public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) { - return tonnespercubicmillimeter.HasValue ? FromTonnesPerCubicMillimeter(tonnespercubicmillimeter.Value) : default(Density?); + double value = (double) poundsperusgallon; + return new Density(value, DensityUnit.PoundPerUSGallon); + } + /// + /// Get Density from SlugsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new Density(value, DensityUnit.SlugPerCubicFoot); + } + /// + /// Get Density from TonnesPerCubicCentimeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new Density(value, DensityUnit.TonnePerCubicCentimeter); + } + /// + /// Get Density from TonnesPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new Density(value, DensityUnit.TonnePerCubicMeter); + } + /// + /// Get Density from TonnesPerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) + { + double value = (double) tonnespercubicmillimeter; + return new Density(value, DensityUnit.TonnePerCubicMillimeter); } /// @@ -410,28 +718,156 @@ public partial struct Density : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Density unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Density? From(QuantityValue? value, DensityUnit fromUnit) + public static Density From(QuantityValue value, DensityUnit fromUnit) { - return value.HasValue ? new Density((double)value.Value, fromUnit) : default(Density?); + return new Density((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Density Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Density result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Density result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static DensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static DensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out DensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Density operator -(Density right) @@ -471,6 +907,8 @@ public static string GetAbbreviation(DensityUnit unit, [CanBeNull] IFormatProvid #endregion + #region Equality / IComparable + public static bool operator <=(Density left, Density right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -491,180 +929,290 @@ public static string GetAbbreviation(DensityUnit unit, [CanBeNull] IFormatProvid return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Density, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Density left, Density right) + public static bool operator ==(Density left, Density right) + { + return left.Equals(right); + } + + public static bool operator !=(Density left, Density right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Density, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Density left, Density right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Density other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Density Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Density other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerCubicMeter(x.KilogramsPerCubicMeter + y.KilogramsPerCubicMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Density result) + /// A hash code for the current Density. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Density); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Density to another Density with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Density with the specified unit. + public Density ToUnit(DensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Density(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; + case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; + case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; + case DensityUnit.GramPerCubicMeter: return _value/1e3; + case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; + case DensityUnit.GramPerDeciliter: return _value/1e-1; + case DensityUnit.GramPerLiter: return _value/1; + case DensityUnit.GramPerMilliliter: return _value/1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; + case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; + case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; + case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; + case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; + case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; + case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; + case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return _value*515.378818; + case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; + case DensityUnit.TonnePerCubicMeter: return _value/0.001; + case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(DensityUnit unit) + { + if(Unit == unit) + return _value; - if (unit == DensityUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; + case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; + case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; + case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; + case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; + case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; + case DensityUnit.GramPerLiter: return baseUnitValue*1; + case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; + case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; + case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; + case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; + case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; + case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; + case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; + case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; + case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; + case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; + case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(DensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs index 4a9f4824cf..a492045fa3 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,123 +49,272 @@ namespace UnitsNet /// /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Duration : IComparable, IComparable + public partial struct Duration : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Duration from nullable Days. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromDays(QuantityValue? days) + private readonly DurationUnit? _unit; + + static Duration() { - return days.HasValue ? FromDays(days.Value) : default(Duration?); + BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); } /// - /// Get nullable Duration from nullable Hours. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromHours(QuantityValue? hours) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Duration(double numericValue, DurationUnit unit) { - return hours.HasValue ? FromHours(hours.Value) : default(Duration?); + if(unit == DurationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Duration, which is Second. All conversions go via this value. + /// + public static DurationUnit BaseUnit => DurationUnit.Second; + + /// + /// Represents the largest possible value of Duration + /// + public static Duration MaxValue => new Duration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Duration + /// + public static Duration MinValue => new Duration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Duration; + + /// + /// All units of measurement for the Duration quantity. + /// + public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Duration Zero => new Duration(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable Duration from nullable Microseconds. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromMicroseconds(QuantityValue? microseconds) + public QuantityType Type => Duration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Duration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Duration in Days. + /// + public double Days => As(DurationUnit.Day); + + /// + /// Get Duration in Hours. + /// + public double Hours => As(DurationUnit.Hour); + + /// + /// Get Duration in Microseconds. + /// + public double Microseconds => As(DurationUnit.Microsecond); + + /// + /// Get Duration in Milliseconds. + /// + public double Milliseconds => As(DurationUnit.Millisecond); + + /// + /// Get Duration in Minutes. + /// + public double Minutes => As(DurationUnit.Minute); + + /// + /// Get Duration in Months30. + /// + public double Months30 => As(DurationUnit.Month30); + + /// + /// Get Duration in Nanoseconds. + /// + public double Nanoseconds => As(DurationUnit.Nanosecond); + + /// + /// Get Duration in Seconds. + /// + public double Seconds => As(DurationUnit.Second); + + /// + /// Get Duration in Weeks. + /// + public double Weeks => As(DurationUnit.Week); + + /// + /// Get Duration in Years365. + /// + public double Years365 => As(DurationUnit.Year365); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DurationUnit unit) { - return microseconds.HasValue ? FromMicroseconds(microseconds.Value) : default(Duration?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Duration from nullable Milliseconds. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromMilliseconds(QuantityValue? milliseconds) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(DurationUnit unit, [CanBeNull] IFormatProvider provider) { - return milliseconds.HasValue ? FromMilliseconds(milliseconds.Value) : default(Duration?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Duration from nullable Minutes. + /// Get Duration from Days. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromMinutes(QuantityValue? minutes) + /// If value is NaN or Infinity. + public static Duration FromDays(QuantityValue days) { - return minutes.HasValue ? FromMinutes(minutes.Value) : default(Duration?); + double value = (double) days; + return new Duration(value, DurationUnit.Day); } - /// - /// Get nullable Duration from nullable Months. + /// Get Duration from Hours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromMonths(QuantityValue? months) + /// If value is NaN or Infinity. + public static Duration FromHours(QuantityValue hours) { - return months.HasValue ? FromMonths(months.Value) : default(Duration?); + double value = (double) hours; + return new Duration(value, DurationUnit.Hour); } - /// - /// Get nullable Duration from nullable Months30. + /// Get Duration from Microseconds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromMonths30(QuantityValue? months30) + /// If value is NaN or Infinity. + public static Duration FromMicroseconds(QuantityValue microseconds) { - return months30.HasValue ? FromMonths30(months30.Value) : default(Duration?); + double value = (double) microseconds; + return new Duration(value, DurationUnit.Microsecond); } - /// - /// Get nullable Duration from nullable Nanoseconds. + /// Get Duration from Milliseconds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromNanoseconds(QuantityValue? nanoseconds) + /// If value is NaN or Infinity. + public static Duration FromMilliseconds(QuantityValue milliseconds) { - return nanoseconds.HasValue ? FromNanoseconds(nanoseconds.Value) : default(Duration?); + double value = (double) milliseconds; + return new Duration(value, DurationUnit.Millisecond); } - /// - /// Get nullable Duration from nullable Seconds. + /// Get Duration from Minutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromSeconds(QuantityValue? seconds) + /// If value is NaN or Infinity. + public static Duration FromMinutes(QuantityValue minutes) { - return seconds.HasValue ? FromSeconds(seconds.Value) : default(Duration?); + double value = (double) minutes; + return new Duration(value, DurationUnit.Minute); } - /// - /// Get nullable Duration from nullable Weeks. + /// Get Duration from Months30. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromWeeks(QuantityValue? weeks) + /// If value is NaN or Infinity. + public static Duration FromMonths30(QuantityValue months30) { - return weeks.HasValue ? FromWeeks(weeks.Value) : default(Duration?); + double value = (double) months30; + return new Duration(value, DurationUnit.Month30); } - /// - /// Get nullable Duration from nullable Years. + /// Get Duration from Nanoseconds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromYears(QuantityValue? years) + /// If value is NaN or Infinity. + public static Duration FromNanoseconds(QuantityValue nanoseconds) { - return years.HasValue ? FromYears(years.Value) : default(Duration?); + double value = (double) nanoseconds; + return new Duration(value, DurationUnit.Nanosecond); + } + /// + /// Get Duration from Seconds. + /// + /// If value is NaN or Infinity. + public static Duration FromSeconds(QuantityValue seconds) + { + double value = (double) seconds; + return new Duration(value, DurationUnit.Second); + } + /// + /// Get Duration from Weeks. + /// + /// If value is NaN or Infinity. + public static Duration FromWeeks(QuantityValue weeks) + { + double value = (double) weeks; + return new Duration(value, DurationUnit.Week); } - /// - /// Get nullable Duration from nullable Years365. + /// Get Duration from Years365. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Duration? FromYears365(QuantityValue? years365) + /// If value is NaN or Infinity. + public static Duration FromYears365(QuantityValue years365) { - return years365.HasValue ? FromYears365(years365.Value) : default(Duration?); + double value = (double) years365; + return new Duration(value, DurationUnit.Year365); } /// @@ -176,28 +323,156 @@ public partial struct Duration : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Duration unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Duration? From(QuantityValue? value, DurationUnit fromUnit) + public static Duration From(QuantityValue value, DurationUnit fromUnit) { - return value.HasValue ? new Duration((double)value.Value, fromUnit) : default(Duration?); + return new Duration((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DurationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Duration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Duration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Duration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static DurationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static DurationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DurationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out DurationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Duration operator -(Duration right) @@ -237,6 +512,8 @@ public static string GetAbbreviation(DurationUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(Duration left, Duration right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -257,180 +534,234 @@ public static string GetAbbreviation(DurationUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Duration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Duration left, Duration right) + public static bool operator ==(Duration left, Duration right) + { + return left.Equals(right); + } + + public static bool operator !=(Duration left, Duration right) + { + return !(left == right); + } + + 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 + public int CompareTo(Duration other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Duration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Duration left, Duration right) + public override bool Equals(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + if(obj is null || !(obj is Duration objDuration)) + return false; + + return Equals(objDuration); } - #region Parsing + public bool Equals(Duration other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Duration Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Duration other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DurationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSeconds(x.Seconds + y.Seconds)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Duration result) + /// A hash code for the current Duration. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Duration); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DurationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Duration to another Duration with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Duration with the specified unit. + public Duration ToUnit(DurationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Duration(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DurationUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case DurationUnit.Day: return _value*24*3600; + case DurationUnit.Hour: return _value*3600; + case DurationUnit.Microsecond: return (_value) * 1e-6d; + case DurationUnit.Millisecond: return (_value) * 1e-3d; + case DurationUnit.Minute: return _value*60; + case DurationUnit.Month30: return _value*30*24*3600; + case DurationUnit.Nanosecond: return (_value) * 1e-9d; + case DurationUnit.Second: return _value; + case DurationUnit.Week: return _value*7*24*3600; + case DurationUnit.Year365: return _value*365*24*3600; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(DurationUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == DurationUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DurationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DurationUnit.Day: return baseUnitValue/(24*3600); + case DurationUnit.Hour: return baseUnitValue/3600; + case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; + case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; + case DurationUnit.Minute: return baseUnitValue/60; + case DurationUnit.Month30: return baseUnitValue/(30*24*3600); + case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; + case DurationUnit.Second: return baseUnitValue; + case DurationUnit.Week: return baseUnitValue/(7*24*3600); + case DurationUnit.Year365: return baseUnitValue/(365*24*3600); + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(DurationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs index b3dcfa5541..c6f68cbcb4 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,69 +49,219 @@ namespace UnitsNet /// /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct DynamicViscosity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity + /// + public partial struct DynamicViscosity : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable DynamicViscosity from nullable Centipoise. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromCentipoise(QuantityValue? centipoise) + private readonly DynamicViscosityUnit? _unit; + + static DynamicViscosity() { - return centipoise.HasValue ? FromCentipoise(centipoise.Value) : default(DynamicViscosity?); + BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); } /// - /// Get nullable DynamicViscosity from nullable MicropascalSeconds. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromMicropascalSeconds(QuantityValue? micropascalseconds) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public DynamicViscosity(double numericValue, DynamicViscosityUnit unit) { - return micropascalseconds.HasValue ? FromMicropascalSeconds(micropascalseconds.Value) : default(DynamicViscosity?); + if(unit == DynamicViscosityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + /// - /// Get nullable DynamicViscosity from nullable MillipascalSeconds. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromMillipascalSeconds(QuantityValue? millipascalseconds) + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. + /// + public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; + + /// + /// Represents the largest possible value of DynamicViscosity + /// + public static DynamicViscosity MaxValue => new DynamicViscosity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of DynamicViscosity + /// + public static DynamicViscosity MinValue => new DynamicViscosity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.DynamicViscosity; + + /// + /// All units of measurement for the DynamicViscosity quantity. + /// + public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// + public static DynamicViscosity Zero => new DynamicViscosity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => DynamicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get DynamicViscosity in Centipoise. + /// + public double Centipoise => As(DynamicViscosityUnit.Centipoise); + + /// + /// Get DynamicViscosity in MicropascalSeconds. + /// + public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); + + /// + /// Get DynamicViscosity in MillipascalSeconds. + /// + public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); + + /// + /// Get DynamicViscosity in NewtonSecondsPerMeterSquared. + /// + public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); + + /// + /// Get DynamicViscosity in PascalSeconds. + /// + public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); + + /// + /// Get DynamicViscosity in Poise. + /// + public double Poise => As(DynamicViscosityUnit.Poise); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(DynamicViscosityUnit unit) { - return millipascalseconds.HasValue ? FromMillipascalSeconds(millipascalseconds.Value) : default(DynamicViscosity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable DynamicViscosity from nullable NewtonSecondsPerMeterSquared. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromNewtonSecondsPerMeterSquared(QuantityValue? newtonsecondspermetersquared) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider) { - return newtonsecondspermetersquared.HasValue ? FromNewtonSecondsPerMeterSquared(newtonsecondspermetersquared.Value) : default(DynamicViscosity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable DynamicViscosity from nullable PascalSeconds. + /// Get DynamicViscosity from Centipoise. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromPascalSeconds(QuantityValue? pascalseconds) + /// If value is NaN or Infinity. + public static DynamicViscosity FromCentipoise(QuantityValue centipoise) { - return pascalseconds.HasValue ? FromPascalSeconds(pascalseconds.Value) : default(DynamicViscosity?); + double value = (double) centipoise; + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); + } + /// + /// Get DynamicViscosity from MicropascalSeconds. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) + { + double value = (double) micropascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); } - /// - /// Get nullable DynamicViscosity from nullable Poise. + /// Get DynamicViscosity from MillipascalSeconds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static DynamicViscosity? FromPoise(QuantityValue? poise) + /// If value is NaN or Infinity. + public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) { - return poise.HasValue ? FromPoise(poise.Value) : default(DynamicViscosity?); + double value = (double) millipascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); + } + /// + /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) + { + double value = (double) newtonsecondspermetersquared; + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); + } + /// + /// Get DynamicViscosity from PascalSeconds. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) + { + double value = (double) pascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); + } + /// + /// Get DynamicViscosity from Poise. + /// + /// If value is NaN or Infinity. + public static DynamicViscosity FromPoise(QuantityValue poise) + { + double value = (double) poise; + return new DynamicViscosity(value, DynamicViscosityUnit.Poise); } /// @@ -122,28 +270,156 @@ public partial struct DynamicViscosity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// DynamicViscosity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static DynamicViscosity? From(QuantityValue? value, DynamicViscosityUnit fromUnit) + public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) { - return value.HasValue ? new DynamicViscosity((double)value.Value, fromUnit) : default(DynamicViscosity?); + return new DynamicViscosity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static DynamicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out DynamicViscosity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static DynamicViscosityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static DynamicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out DynamicViscosityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static DynamicViscosity operator -(DynamicViscosity right) @@ -183,6 +459,8 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] IFor #endregion + #region Equality / IComparable + public static bool operator <=(DynamicViscosity left, DynamicViscosity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -203,180 +481,226 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] IFor return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(DynamicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(DynamicViscosity left, DynamicViscosity right) + public static bool operator ==(DynamicViscosity left, DynamicViscosity right) + { + return left.Equals(right); + } + + public static bool operator !=(DynamicViscosity left, DynamicViscosity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); + } + + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(DynamicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(DynamicViscosity left, DynamicViscosity right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(DynamicViscosity other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static DynamicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - DynamicViscosityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonSecondsPerMeterSquared(x.NewtonSecondsPerMeterSquared + y.NewtonSecondsPerMeterSquared)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out DynamicViscosity result) + /// A hash code for the current DynamicViscosity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(DynamicViscosity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DynamicViscosityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A DynamicViscosity with the specified unit. + public DynamicViscosity ToUnit(DynamicViscosityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new DynamicViscosity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DynamicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; + case DynamicViscosityUnit.PascalSecond: return _value; + case DynamicViscosityUnit.Poise: return _value/10; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(DynamicViscosityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == DynamicViscosityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DynamicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; + case DynamicViscosityUnit.PascalSecond: return baseUnitValue; + case DynamicViscosityUnit.Poise: return baseUnitValue*10; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs index 02f5b7ed8a..0aa8614684 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,188 @@ namespace UnitsNet /// /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricAdmittance : IComparable, IComparable + public partial struct ElectricAdmittance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricAdmittanceUnit? _unit; + + static ElectricAdmittance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } /// - /// Get nullable ElectricAdmittance from nullable Microsiemens. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricAdmittance? FromMicrosiemens(QuantityValue? microsiemens) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricAdmittance(double numericValue, ElectricAdmittanceUnit unit) { - return microsiemens.HasValue ? FromMicrosiemens(microsiemens.Value) : default(ElectricAdmittance?); + if(unit == ElectricAdmittanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. + /// + public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; + + /// + /// Represents the largest possible value of ElectricAdmittance + /// + public static ElectricAdmittance MaxValue => new ElectricAdmittance(double.MaxValue, BaseUnit); + /// - /// Get nullable ElectricAdmittance from nullable Millisiemens. + /// Represents the smallest possible value of ElectricAdmittance /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricAdmittance? FromMillisiemens(QuantityValue? millisiemens) + public static ElectricAdmittance MinValue => new ElectricAdmittance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricAdmittance; + + /// + /// All units of measurement for the ElectricAdmittance quantity. + /// + public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricAdmittance Zero => new ElectricAdmittance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricAdmittance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricAdmittance in Microsiemens. + /// + public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); + + /// + /// Get ElectricAdmittance in Millisiemens. + /// + public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); + + /// + /// Get ElectricAdmittance in Nanosiemens. + /// + public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); + + /// + /// Get ElectricAdmittance in Siemens. + /// + public double Siemens => As(ElectricAdmittanceUnit.Siemens); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricAdmittanceUnit unit) { - return millisiemens.HasValue ? FromMillisiemens(millisiemens.Value) : default(ElectricAdmittance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricAdmittance from nullable Nanosiemens. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricAdmittance? FromNanosiemens(QuantityValue? nanosiemens) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider) { - return nanosiemens.HasValue ? FromNanosiemens(nanosiemens.Value) : default(ElectricAdmittance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricAdmittance from Microsiemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); + } + /// + /// Get ElectricAdmittance from Millisiemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) + { + double value = (double) millisiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); + } /// - /// Get nullable ElectricAdmittance from nullable Siemens. + /// Get ElectricAdmittance from Nanosiemens. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricAdmittance? FromSiemens(QuantityValue? siemens) + /// If value is NaN or Infinity. + public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) { - return siemens.HasValue ? FromSiemens(siemens.Value) : default(ElectricAdmittance?); + double value = (double) nanosiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); + } + /// + /// Get ElectricAdmittance from Siemens. + /// + /// If value is NaN or Infinity. + public static ElectricAdmittance FromSiemens(QuantityValue siemens) + { + double value = (double) siemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); } /// @@ -104,28 +239,156 @@ public partial struct ElectricAdmittance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricAdmittance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricAdmittance? From(QuantityValue? value, ElectricAdmittanceUnit fromUnit) + public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) { - return value.HasValue ? new ElectricAdmittance((double)value.Value, fromUnit) : default(ElectricAdmittance?); + return new ElectricAdmittance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricAdmittance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricAdmittance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricAdmittanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricAdmittanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricAdmittance operator -(ElectricAdmittance right) @@ -165,6 +428,8 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] IF #endregion + #region Equality / IComparable + public static bool operator <=(ElectricAdmittance left, ElectricAdmittance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +450,222 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] IF return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricAdmittance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) + public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricAdmittance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) + public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricAdmittance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricAdmittance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricAdmittanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemens(x.Siemens + y.Siemens)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricAdmittance result) + /// A hash code for the current ElectricAdmittance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricAdmittance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricAdmittanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricAdmittance with the specified unit. + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricAdmittance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricAdmittanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricAdmittanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs index 624b58945d..ad8c89f4e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricCharge : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Electric_charge + /// + public partial struct ElectricCharge : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeUnit? _unit; + + static ElectricCharge() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricCharge(double numericValue, ElectricChargeUnit unit) + { + if(unit == ElectricChargeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. + /// + public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; + + /// + /// Represents the largest possible value of ElectricCharge + /// + public static ElectricCharge MaxValue => new ElectricCharge(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCharge + /// + public static ElectricCharge MinValue => new ElectricCharge(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCharge; + + /// + /// All units of measurement for the ElectricCharge quantity. + /// + public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. + /// + public static ElectricCharge Zero => new ElectricCharge(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCharge.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCharge in Coulombs. + /// + public double Coulombs => As(ElectricChargeUnit.Coulomb); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricCharge from nullable Coulombs. + /// Get ElectricCharge from Coulombs. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCharge? FromCoulombs(QuantityValue? coulombs) + /// If value is NaN or Infinity. + public static ElectricCharge FromCoulombs(QuantityValue coulombs) { - return coulombs.HasValue ? FromCoulombs(coulombs.Value) : default(ElectricCharge?); + double value = (double) coulombs; + return new ElectricCharge(value, ElectricChargeUnit.Coulomb); } /// @@ -77,28 +200,156 @@ public partial struct ElectricCharge : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ElectricCharge unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCharge? From(QuantityValue? value, ElectricChargeUnit fromUnit) + public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) { - return value.HasValue ? new ElectricCharge((double)value.Value, fromUnit) : default(ElectricCharge?); + return new ElectricCharge((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCharge Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCharge result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCharge result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricChargeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricChargeUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricChargeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricCharge operator -(ElectricCharge right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(ElectricCharge left, ElectricCharge right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCharge, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricCharge left, ElectricCharge right) + public static bool operator ==(ElectricCharge left, ElectricCharge right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCharge, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricCharge left, ElectricCharge right) + public static bool operator !=(ElectricCharge left, ElectricCharge right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricCharge other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCharge Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricCharge other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricChargeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCoulombs(x.Coulombs + y.Coulombs)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCharge result) + /// A hash code for the current ElectricCharge. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricCharge); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricCharge to another ElectricCharge with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricCharge with the specified unit. + public ElectricCharge ToUnit(ElectricChargeUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricCharge(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ElectricChargeUnit.Coulomb: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ElectricChargeUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricChargeUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricChargeUnit.Coulomb: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs index f7e10c22e4..c7f07b4c82 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In electromagnetism, charge density is a measure of the amount of electric charge per unit length, surface area, or volume. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricChargeDensity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Charge_density + /// + public partial struct ElectricChargeDensity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeDensityUnit? _unit; + + static ElectricChargeDensity() + { + BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricChargeDensity(double numericValue, ElectricChargeDensityUnit unit) + { + if(unit == ElectricChargeDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. + /// + public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; + + /// + /// Represents the largest possible value of ElectricChargeDensity + /// + public static ElectricChargeDensity MaxValue => new ElectricChargeDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricChargeDensity + /// + public static ElectricChargeDensity MinValue => new ElectricChargeDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricChargeDensity; + + /// + /// All units of measurement for the ElectricChargeDensity quantity. + /// + public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// + public static ElectricChargeDensity Zero => new ElectricChargeDensity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricChargeDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricChargeDensity in CoulombsPerCubicMeter. + /// + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricChargeDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricChargeDensity from nullable CoulombsPerCubicMeter. + /// Get ElectricChargeDensity from CoulombsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricChargeDensity? FromCoulombsPerCubicMeter(QuantityValue? coulombspercubicmeter) + /// If value is NaN or Infinity. + public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) { - return coulombspercubicmeter.HasValue ? FromCoulombsPerCubicMeter(coulombspercubicmeter.Value) : default(ElectricChargeDensity?); + double value = (double) coulombspercubicmeter; + return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); } /// @@ -77,28 +200,156 @@ public partial struct ElectricChargeDensity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricChargeDensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricChargeDensity? From(QuantityValue? value, ElectricChargeDensityUnit fromUnit) + public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) { - return value.HasValue ? new ElectricChargeDensity((double)value.Value, fromUnit) : default(ElectricChargeDensity?); + return new ElectricChargeDensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricChargeDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricChargeDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricChargeDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricChargeDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricChargeDensity operator -(ElectricChargeDensity right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] #endregion + #region Equality / IComparable + public static bool operator <=(ElectricChargeDensity left, ElectricChargeDensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricChargeDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) + public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricChargeDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) + public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricChargeDensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricChargeDensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricChargeDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCoulombsPerCubicMeter(x.CoulombsPerCubicMeter + y.CoulombsPerCubicMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricChargeDensity result) + /// A hash code for the current ElectricChargeDensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricChargeDensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricChargeDensity with the specified unit. + public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricChargeDensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricChargeDensityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs index 585549b8d0..055e85ca6e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,177 @@ namespace UnitsNet /// /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricConductance : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance + /// + public partial struct ElectricConductance : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductanceUnit? _unit; + + static ElectricConductance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricConductance(double numericValue, ElectricConductanceUnit unit) + { + if(unit == ElectricConductanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. + /// + public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; + + /// + /// Represents the largest possible value of ElectricConductance + /// + public static ElectricConductance MaxValue => new ElectricConductance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricConductance + /// + public static ElectricConductance MinValue => new ElectricConductance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricConductance; + + /// + /// All units of measurement for the ElectricConductance quantity. + /// + public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// + public static ElectricConductance Zero => new ElectricConductance(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable ElectricConductance from nullable Microsiemens. + /// Get ElectricConductance in Microsiemens. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricConductance? FromMicrosiemens(QuantityValue? microsiemens) + public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); + + /// + /// Get ElectricConductance in Millisiemens. + /// + public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); + + /// + /// Get ElectricConductance in Siemens. + /// + public double Siemens => As(ElectricConductanceUnit.Siemens); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductanceUnit unit) { - return microsiemens.HasValue ? FromMicrosiemens(microsiemens.Value) : default(ElectricConductance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricConductance from nullable Millisiemens. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricConductance? FromMillisiemens(QuantityValue? millisiemens) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider) { - return millisiemens.HasValue ? FromMillisiemens(millisiemens.Value) : default(ElectricConductance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricConductance from Microsiemens. + /// + /// If value is NaN or Infinity. + public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); + } /// - /// Get nullable ElectricConductance from nullable Siemens. + /// Get ElectricConductance from Millisiemens. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricConductance? FromSiemens(QuantityValue? siemens) + /// If value is NaN or Infinity. + public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) { - return siemens.HasValue ? FromSiemens(siemens.Value) : default(ElectricConductance?); + double value = (double) millisiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); + } + /// + /// Get ElectricConductance from Siemens. + /// + /// If value is NaN or Infinity. + public static ElectricConductance FromSiemens(QuantityValue siemens) + { + double value = (double) siemens; + return new ElectricConductance(value, ElectricConductanceUnit.Siemens); } /// @@ -95,28 +228,156 @@ public partial struct ElectricConductance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricConductance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductance? From(QuantityValue? value, ElectricConductanceUnit fromUnit) + public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) { - return value.HasValue ? new ElectricConductance((double)value.Value, fromUnit) : default(ElectricConductance?); + return new ElectricConductance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricConductance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricConductanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricConductanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricConductanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricConductance operator -(ElectricConductance right) @@ -156,6 +417,8 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(ElectricConductance left, ElectricConductance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +439,220 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricConductance left, ElectricConductance right) + public static bool operator ==(ElectricConductance left, ElectricConductance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricConductance left, ElectricConductance right) + public static bool operator !=(ElectricConductance left, ElectricConductance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricConductance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricConductance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricConductanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemens(x.Siemens + y.Siemens)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductance result) + /// A hash code for the current ElectricConductance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricConductance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricConductance to another ElectricConductance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricConductance with the specified unit. + public ElectricConductance ToUnit(ElectricConductanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricConductance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricConductanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs index 2f9d6a230c..2bf2645bb3 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricConductivity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + public partial struct ElectricConductivity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductivityUnit? _unit; + + static ElectricConductivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricConductivity(double numericValue, ElectricConductivityUnit unit) + { + if(unit == ElectricConductivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. + /// + public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; + + /// + /// Represents the largest possible value of ElectricConductivity + /// + public static ElectricConductivity MaxValue => new ElectricConductivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricConductivity + /// + public static ElectricConductivity MinValue => new ElectricConductivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricConductivity; + + /// + /// All units of measurement for the ElectricConductivity quantity. + /// + public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. + /// + public static ElectricConductivity Zero => new ElectricConductivity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricConductivity in SiemensPerMeter. + /// + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricConductivity from nullable SiemensPerMeter. + /// Get ElectricConductivity from SiemensPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricConductivity? FromSiemensPerMeter(QuantityValue? siemenspermeter) + /// If value is NaN or Infinity. + public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) { - return siemenspermeter.HasValue ? FromSiemensPerMeter(siemenspermeter.Value) : default(ElectricConductivity?); + double value = (double) siemenspermeter; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); } /// @@ -77,28 +200,156 @@ public partial struct ElectricConductivity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricConductivity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricConductivity? From(QuantityValue? value, ElectricConductivityUnit fromUnit) + public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) { - return value.HasValue ? new ElectricConductivity((double)value.Value, fromUnit) : default(ElectricConductivity?); + return new ElectricConductivity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricConductivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricConductivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricConductivity operator -(ElectricConductivity right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] #endregion + #region Equality / IComparable + public static bool operator <=(ElectricConductivity left, ElectricConductivity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricConductivity left, ElectricConductivity right) + public static bool operator ==(ElectricConductivity left, ElectricConductivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricConductivity left, ElectricConductivity right) + public static bool operator !=(ElectricConductivity left, ElectricConductivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricConductivity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricConductivity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricConductivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSiemensPerMeter(x.SiemensPerMeter + y.SiemensPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricConductivity result) + /// A hash code for the current ElectricConductivity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricConductivity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricConductivity with the specified unit. + public ElectricConductivity ToUnit(ElectricConductivityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricConductivity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ElectricConductivityUnit.SiemensPerMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ElectricConductivityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricConductivityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs index 810d0fa05c..297cf7cb67 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,244 @@ namespace UnitsNet /// /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricCurrent : IComparable, IComparable + public partial struct ElectricCurrent : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ElectricCurrent from nullable Amperes. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromAmperes(QuantityValue? amperes) + private readonly ElectricCurrentUnit? _unit; + + static ElectricCurrent() { - return amperes.HasValue ? FromAmperes(amperes.Value) : default(ElectricCurrent?); + BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); } /// - /// Get nullable ElectricCurrent from nullable Centiamperes. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromCentiamperes(QuantityValue? centiamperes) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricCurrent(double numericValue, ElectricCurrentUnit unit) { - return centiamperes.HasValue ? FromCentiamperes(centiamperes.Value) : default(ElectricCurrent?); + if(unit == ElectricCurrentUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. + /// + public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; + + /// + /// Represents the largest possible value of ElectricCurrent + /// + public static ElectricCurrent MaxValue => new ElectricCurrent(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrent + /// + public static ElectricCurrent MinValue => new ElectricCurrent(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrent; + + /// + /// All units of measurement for the ElectricCurrent quantity. + /// + public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. + /// + public static ElectricCurrent Zero => new ElectricCurrent(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable ElectricCurrent from nullable Kiloamperes. + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrent.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrent in Amperes. + /// + public double Amperes => As(ElectricCurrentUnit.Ampere); + + /// + /// Get ElectricCurrent in Centiamperes. + /// + public double Centiamperes => As(ElectricCurrentUnit.Centiampere); + + /// + /// Get ElectricCurrent in Kiloamperes. + /// + public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); + + /// + /// Get ElectricCurrent in Megaamperes. + /// + public double Megaamperes => As(ElectricCurrentUnit.Megaampere); + + /// + /// Get ElectricCurrent in Microamperes. + /// + public double Microamperes => As(ElectricCurrentUnit.Microampere); + + /// + /// Get ElectricCurrent in Milliamperes. + /// + public double Milliamperes => As(ElectricCurrentUnit.Milliampere); + + /// + /// Get ElectricCurrent in Nanoamperes. + /// + public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); + + /// + /// Get ElectricCurrent in Picoamperes. + /// + public double Picoamperes => As(ElectricCurrentUnit.Picoampere); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromKiloamperes(QuantityValue? kiloamperes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentUnit unit) { - return kiloamperes.HasValue ? FromKiloamperes(kiloamperes.Value) : default(ElectricCurrent?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricCurrent from nullable Megaamperes. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromMegaamperes(QuantityValue? megaamperes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider) { - return megaamperes.HasValue ? FromMegaamperes(megaamperes.Value) : default(ElectricCurrent?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable ElectricCurrent from nullable Microamperes. + /// Get ElectricCurrent from Amperes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromMicroamperes(QuantityValue? microamperes) + /// If value is NaN or Infinity. + public static ElectricCurrent FromAmperes(QuantityValue amperes) { - return microamperes.HasValue ? FromMicroamperes(microamperes.Value) : default(ElectricCurrent?); + double value = (double) amperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); } - /// - /// Get nullable ElectricCurrent from nullable Milliamperes. + /// Get ElectricCurrent from Centiamperes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromMilliamperes(QuantityValue? milliamperes) + /// If value is NaN or Infinity. + public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) { - return milliamperes.HasValue ? FromMilliamperes(milliamperes.Value) : default(ElectricCurrent?); + double value = (double) centiamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); } - /// - /// Get nullable ElectricCurrent from nullable Nanoamperes. + /// Get ElectricCurrent from Kiloamperes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromNanoamperes(QuantityValue? nanoamperes) + /// If value is NaN or Infinity. + public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) { - return nanoamperes.HasValue ? FromNanoamperes(nanoamperes.Value) : default(ElectricCurrent?); + double value = (double) kiloamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); + } + /// + /// Get ElectricCurrent from Megaamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) + { + double value = (double) megaamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); + } + /// + /// Get ElectricCurrent from Microamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) + { + double value = (double) microamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); + } + /// + /// Get ElectricCurrent from Milliamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) + { + double value = (double) milliamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); } - /// - /// Get nullable ElectricCurrent from nullable Picoamperes. + /// Get ElectricCurrent from Nanoamperes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrent? FromPicoamperes(QuantityValue? picoamperes) + /// If value is NaN or Infinity. + public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) { - return picoamperes.HasValue ? FromPicoamperes(picoamperes.Value) : default(ElectricCurrent?); + double value = (double) nanoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); + } + /// + /// Get ElectricCurrent from Picoamperes. + /// + /// If value is NaN or Infinity. + public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) + { + double value = (double) picoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); } /// @@ -140,28 +295,156 @@ public partial struct ElectricCurrent : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricCurrent unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrent? From(QuantityValue? value, ElectricCurrentUnit fromUnit) + public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) { - return value.HasValue ? new ElectricCurrent((double)value.Value, fromUnit) : default(ElectricCurrent?); + return new ElectricCurrent((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrent Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrent result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricCurrentUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrentUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricCurrentUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricCurrent operator -(ElectricCurrent right) @@ -201,6 +484,8 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] IForm #endregion + #region Equality / IComparable + public static bool operator <=(ElectricCurrent left, ElectricCurrent right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +506,230 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] IForm return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrent, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricCurrent left, ElectricCurrent right) + public static bool operator ==(ElectricCurrent left, ElectricCurrent right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrent, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricCurrent left, ElectricCurrent right) + public static bool operator !=(ElectricCurrent left, ElectricCurrent right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricCurrent other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrent Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricCurrent other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperes(x.Amperes + y.Amperes)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrent result) + /// A hash code for the current ElectricCurrent. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricCurrent); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricCurrent with the specified unit. + public ElectricCurrent ToUnit(ElectricCurrentUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricCurrent(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricCurrentUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs index f13896f7a7..454421c96a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In electromagnetism, current density is the electric current per unit area of cross section. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricCurrentDensity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Current_density + /// + public partial struct ElectricCurrentDensity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentDensityUnit? _unit; + + static ElectricCurrentDensity() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricCurrentDensity(double numericValue, ElectricCurrentDensityUnit unit) + { + if(unit == ElectricCurrentDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. + /// + public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; + + /// + /// Represents the largest possible value of ElectricCurrentDensity + /// + public static ElectricCurrentDensity MaxValue => new ElectricCurrentDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrentDensity + /// + public static ElectricCurrentDensity MinValue => new ElectricCurrentDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrentDensity; + + /// + /// All units of measurement for the ElectricCurrentDensity quantity. + /// + public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// + public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentDensity in AmperesPerSquareMeter. + /// + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricCurrentDensity from nullable AmperesPerSquareMeter. + /// Get ElectricCurrentDensity from AmperesPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrentDensity? FromAmperesPerSquareMeter(QuantityValue? amperespersquaremeter) + /// If value is NaN or Infinity. + public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) { - return amperespersquaremeter.HasValue ? FromAmperesPerSquareMeter(amperespersquaremeter.Value) : default(ElectricCurrentDensity?); + double value = (double) amperespersquaremeter; + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); } /// @@ -77,28 +200,156 @@ public partial struct ElectricCurrentDensity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricCurrentDensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrentDensity? From(QuantityValue? value, ElectricCurrentDensityUnit fromUnit) + public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) { - return value.HasValue ? new ElectricCurrentDensity((double)value.Value, fromUnit) : default(ElectricCurrentDensity?); + return new ElectricCurrentDensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrentDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricCurrentDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricCurrentDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricCurrentDensity operator -(ElectricCurrentDensity right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull #endregion + #region Equality / IComparable + public static bool operator <=(ElectricCurrentDensity left, ElectricCurrentDensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) + public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) + public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricCurrentDensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentDensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerSquareMeter(x.AmperesPerSquareMeter + y.AmperesPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentDensity result) + /// A hash code for the current ElectricCurrentDensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricCurrentDensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricCurrentDensity with the specified unit. + public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricCurrentDensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ElectricCurrentDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricCurrentDensityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs index 222fbb613f..45c50ff74e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,146 @@ namespace UnitsNet /// /// In electromagnetism, the current gradient describes how the current changes in time. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricCurrentGradient : IComparable, IComparable + public partial struct ElectricCurrentGradient : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentGradientUnit? _unit; + + static ElectricCurrentGradient() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricCurrentGradient(double numericValue, ElectricCurrentGradientUnit unit) + { + if(unit == ElectricCurrentGradientUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. + /// + public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; + + /// + /// Represents the largest possible value of ElectricCurrentGradient + /// + public static ElectricCurrentGradient MaxValue => new ElectricCurrentGradient(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricCurrentGradient + /// + public static ElectricCurrentGradient MinValue => new ElectricCurrentGradient(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricCurrentGradient; + + /// + /// All units of measurement for the ElectricCurrentGradient quantity. + /// + public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. + /// + public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricCurrentGradient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricCurrentGradient in AmperesPerSecond. + /// + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricCurrentGradientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricCurrentGradient from nullable AmperesPerSecond. + /// Get ElectricCurrentGradient from AmperesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricCurrentGradient? FromAmperesPerSecond(QuantityValue? amperespersecond) + /// If value is NaN or Infinity. + public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) { - return amperespersecond.HasValue ? FromAmperesPerSecond(amperespersecond.Value) : default(ElectricCurrentGradient?); + double value = (double) amperespersecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); } /// @@ -77,28 +197,156 @@ public partial struct ElectricCurrentGradient : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricCurrentGradient unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricCurrentGradient? From(QuantityValue? value, ElectricCurrentGradientUnit fromUnit) + public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) { - return value.HasValue ? new ElectricCurrentGradient((double)value.Value, fromUnit) : default(ElectricCurrentGradient?); + return new ElectricCurrentGradient((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrentGradient Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentGradient result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricCurrentGradientUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricCurrentGradientUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricCurrentGradient operator -(ElectricCurrentGradient right) @@ -138,6 +386,8 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNul #endregion + #region Equality / IComparable + public static bool operator <=(ElectricCurrentGradient left, ElectricCurrentGradient right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +408,216 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNul return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentGradient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) + public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricCurrentGradient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) + public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricCurrentGradient other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentGradient Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricCurrentGradientUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerSecond(x.AmperesPerSecond + y.AmperesPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricCurrentGradient result) + /// A hash code for the current ElectricCurrentGradient. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricCurrentGradient); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentGradientUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricCurrentGradient with the specified unit. + public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricCurrentGradient(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ElectricCurrentGradientUnit.AmperePerSecond: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ElectricCurrentGradientUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricCurrentGradientUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentGradientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs index 9ac2ebd027..92ad660991 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricField : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Electric_field + /// + public partial struct ElectricField : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricFieldUnit? _unit; + + static ElectricField() + { + BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricField(double numericValue, ElectricFieldUnit unit) + { + if(unit == ElectricFieldUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. + /// + public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; + + /// + /// Represents the largest possible value of ElectricField + /// + public static ElectricField MaxValue => new ElectricField(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricField + /// + public static ElectricField MinValue => new ElectricField(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricField; + + /// + /// All units of measurement for the ElectricField quantity. + /// + public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. + /// + public static ElectricField Zero => new ElectricField(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricField in VoltsPerMeter. + /// + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable ElectricField from nullable VoltsPerMeter. + /// Get ElectricField from VoltsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricField? FromVoltsPerMeter(QuantityValue? voltspermeter) + /// If value is NaN or Infinity. + public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) { - return voltspermeter.HasValue ? FromVoltsPerMeter(voltspermeter.Value) : default(ElectricField?); + double value = (double) voltspermeter; + return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); } /// @@ -77,28 +200,156 @@ public partial struct ElectricField : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ElectricField unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricField? From(QuantityValue? value, ElectricFieldUnit fromUnit) + public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) { - return value.HasValue ? new ElectricField((double)value.Value, fromUnit) : default(ElectricField?); + return new ElectricField((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricField Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricField result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricFieldUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricFieldUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricFieldUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricField operator -(ElectricField right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(ElectricField left, ElectricField right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricField left, ElectricField right) + public static bool operator ==(ElectricField left, ElectricField right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricField left, ElectricField right) + public static bool operator !=(ElectricField left, ElectricField right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricField other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricField Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricField other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricFieldUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsPerMeter(x.VoltsPerMeter + y.VoltsPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricField result) + /// A hash code for the current ElectricField. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricField); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricFieldUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricField to another ElectricField with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricField with the specified unit. + public ElectricField ToUnit(ElectricFieldUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricField(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricFieldUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricFieldUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs index a218a202b8..b8122cd354 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,191 @@ namespace UnitsNet /// /// Inductance is a property of an electrical conductor which opposes a change in current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricInductance : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Inductance + /// + public partial struct ElectricInductance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricInductanceUnit? _unit; + + static ElectricInductance() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); + } /// - /// Get nullable ElectricInductance from nullable Henries. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricInductance? FromHenries(QuantityValue? henries) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricInductance(double numericValue, ElectricInductanceUnit unit) { - return henries.HasValue ? FromHenries(henries.Value) : default(ElectricInductance?); + if(unit == ElectricInductanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. + /// + public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; + + /// + /// Represents the largest possible value of ElectricInductance + /// + public static ElectricInductance MaxValue => new ElectricInductance(double.MaxValue, BaseUnit); + /// - /// Get nullable ElectricInductance from nullable Microhenries. + /// Represents the smallest possible value of ElectricInductance /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricInductance? FromMicrohenries(QuantityValue? microhenries) + public static ElectricInductance MinValue => new ElectricInductance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricInductance; + + /// + /// All units of measurement for the ElectricInductance quantity. + /// + public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Henry. + /// + public static ElectricInductance Zero => new ElectricInductance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricInductance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricInductance in Henries. + /// + public double Henries => As(ElectricInductanceUnit.Henry); + + /// + /// Get ElectricInductance in Microhenries. + /// + public double Microhenries => As(ElectricInductanceUnit.Microhenry); + + /// + /// Get ElectricInductance in Millihenries. + /// + public double Millihenries => As(ElectricInductanceUnit.Millihenry); + + /// + /// Get ElectricInductance in Nanohenries. + /// + public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricInductanceUnit unit) { - return microhenries.HasValue ? FromMicrohenries(microhenries.Value) : default(ElectricInductance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricInductance from nullable Millihenries. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricInductance? FromMillihenries(QuantityValue? millihenries) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider) { - return millihenries.HasValue ? FromMillihenries(millihenries.Value) : default(ElectricInductance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricInductance from Henries. + /// + /// If value is NaN or Infinity. + public static ElectricInductance FromHenries(QuantityValue henries) + { + double value = (double) henries; + return new ElectricInductance(value, ElectricInductanceUnit.Henry); + } + /// + /// Get ElectricInductance from Microhenries. + /// + /// If value is NaN or Infinity. + public static ElectricInductance FromMicrohenries(QuantityValue microhenries) + { + double value = (double) microhenries; + return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); + } /// - /// Get nullable ElectricInductance from nullable Nanohenries. + /// Get ElectricInductance from Millihenries. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricInductance? FromNanohenries(QuantityValue? nanohenries) + /// If value is NaN or Infinity. + public static ElectricInductance FromMillihenries(QuantityValue millihenries) { - return nanohenries.HasValue ? FromNanohenries(nanohenries.Value) : default(ElectricInductance?); + double value = (double) millihenries; + return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); + } + /// + /// Get ElectricInductance from Nanohenries. + /// + /// If value is NaN or Infinity. + public static ElectricInductance FromNanohenries(QuantityValue nanohenries) + { + double value = (double) nanohenries; + return new ElectricInductance(value, ElectricInductanceUnit.Nanohenry); } /// @@ -104,28 +242,156 @@ public partial struct ElectricInductance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricInductance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricInductance? From(QuantityValue? value, ElectricInductanceUnit fromUnit) + public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) { - return value.HasValue ? new ElectricInductance((double)value.Value, fromUnit) : default(ElectricInductance?); + return new ElectricInductance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricInductance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricInductance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricInductance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricInductanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricInductanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricInductanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricInductance operator -(ElectricInductance right) @@ -165,6 +431,8 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] IF #endregion + #region Equality / IComparable + public static bool operator <=(ElectricInductance left, ElectricInductance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +453,222 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] IF return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricInductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricInductance left, ElectricInductance right) + public static bool operator ==(ElectricInductance left, ElectricInductance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricInductance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricInductance left, ElectricInductance right) + public static bool operator !=(ElectricInductance left, ElectricInductance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricInductance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricInductance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricInductance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricInductanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHenries(x.Henries + y.Henries)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricInductance result) + /// A hash code for the current ElectricInductance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricInductance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricInductanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricInductance to another ElectricInductance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricInductance with the specified unit. + public ElectricInductance ToUnit(ElectricInductanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricInductance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricInductanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricInductanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricInductanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs index cf4cfc71a4..94bb36db61 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,202 @@ namespace UnitsNet /// /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricPotential : IComparable, IComparable + public partial struct ElectricPotential : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ElectricPotential from nullable Kilovolts. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotential? FromKilovolts(QuantityValue? kilovolts) + private readonly ElectricPotentialUnit? _unit; + + static ElectricPotential() { - return kilovolts.HasValue ? FromKilovolts(kilovolts.Value) : default(ElectricPotential?); + BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); } /// - /// Get nullable ElectricPotential from nullable Megavolts. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotential? FromMegavolts(QuantityValue? megavolts) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricPotential(double numericValue, ElectricPotentialUnit unit) { - return megavolts.HasValue ? FromMegavolts(megavolts.Value) : default(ElectricPotential?); + if(unit == ElectricPotentialUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. + /// + public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; + + /// + /// Represents the largest possible value of ElectricPotential + /// + public static ElectricPotential MaxValue => new ElectricPotential(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotential + /// + public static ElectricPotential MinValue => new ElectricPotential(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotential; + + /// + /// All units of measurement for the ElectricPotential quantity. + /// + public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Volt. + /// + public static ElectricPotential Zero => new ElectricPotential(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotential.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotential in Kilovolts. + /// + public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); + + /// + /// Get ElectricPotential in Megavolts. + /// + public double Megavolts => As(ElectricPotentialUnit.Megavolt); + + /// + /// Get ElectricPotential in Microvolts. + /// + public double Microvolts => As(ElectricPotentialUnit.Microvolt); + + /// + /// Get ElectricPotential in Millivolts. + /// + public double Millivolts => As(ElectricPotentialUnit.Millivolt); + + /// + /// Get ElectricPotential in Volts. + /// + public double Volts => As(ElectricPotentialUnit.Volt); + + #endregion + + #region Static Methods + /// - /// Get nullable ElectricPotential from nullable Microvolts. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotential? FromMicrovolts(QuantityValue? microvolts) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialUnit unit) { - return microvolts.HasValue ? FromMicrovolts(microvolts.Value) : default(ElectricPotential?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricPotential from nullable Millivolts. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotential? FromMillivolts(QuantityValue? millivolts) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider) { - return millivolts.HasValue ? FromMillivolts(millivolts.Value) : default(ElectricPotential?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotential from Kilovolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromKilovolts(QuantityValue kilovolts) + { + double value = (double) kilovolts; + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); + } + /// + /// Get ElectricPotential from Megavolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMegavolts(QuantityValue megavolts) + { + double value = (double) megavolts; + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); + } + /// + /// Get ElectricPotential from Microvolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMicrovolts(QuantityValue microvolts) + { + double value = (double) microvolts; + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); + } + /// + /// Get ElectricPotential from Millivolts. + /// + /// If value is NaN or Infinity. + public static ElectricPotential FromMillivolts(QuantityValue millivolts) + { + double value = (double) millivolts; + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); + } /// - /// Get nullable ElectricPotential from nullable Volts. + /// Get ElectricPotential from Volts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotential? FromVolts(QuantityValue? volts) + /// If value is NaN or Infinity. + public static ElectricPotential FromVolts(QuantityValue volts) { - return volts.HasValue ? FromVolts(volts.Value) : default(ElectricPotential?); + double value = (double) volts; + return new ElectricPotential(value, ElectricPotentialUnit.Volt); } /// @@ -113,28 +253,156 @@ public partial struct ElectricPotential : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricPotential unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotential? From(QuantityValue? value, ElectricPotentialUnit fromUnit) + public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) { - return value.HasValue ? new ElectricPotential((double)value.Value, fromUnit) : default(ElectricPotential?); + return new ElectricPotential((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotential Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotential result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotential result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricPotentialUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotentialUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricPotentialUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricPotential operator -(ElectricPotential right) @@ -174,6 +442,8 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] IFo #endregion + #region Equality / IComparable + public static bool operator <=(ElectricPotential left, ElectricPotential right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +464,224 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] IFo return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotential, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricPotential left, ElectricPotential right) + public static bool operator ==(ElectricPotential left, ElectricPotential right) + { + return left.Equals(right); + } + + public static bool operator !=(ElectricPotential left, ElectricPotential right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotential, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricPotential left, ElectricPotential right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(ElectricPotential other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotential Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricPotential other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVolts(x.Volts + y.Volts)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotential result) + /// A hash code for the current ElectricPotential. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricPotential); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricPotential to another ElectricPotential with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricPotential with the specified unit. + public ElectricPotential ToUnit(ElectricPotentialUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotential(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricPotentialUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs index 168ba84131..decd51b7f0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,202 @@ namespace UnitsNet /// /// The Electric Potential of a system known to use Alternating Current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricPotentialAc : IComparable, IComparable + public partial struct ElectricPotentialAc : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ElectricPotentialAc from nullable KilovoltsAc. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialAc? FromKilovoltsAc(QuantityValue? kilovoltsac) + private readonly ElectricPotentialAcUnit? _unit; + + static ElectricPotentialAc() { - return kilovoltsac.HasValue ? FromKilovoltsAc(kilovoltsac.Value) : default(ElectricPotentialAc?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable ElectricPotentialAc from nullable MegavoltsAc. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialAc? FromMegavoltsAc(QuantityValue? megavoltsac) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit) { - return megavoltsac.HasValue ? FromMegavoltsAc(megavoltsac.Value) : default(ElectricPotentialAc?); + if(unit == ElectricPotentialAcUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. + /// + public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; + + /// + /// Represents the largest possible value of ElectricPotentialAc + /// + public static ElectricPotentialAc MaxValue => new ElectricPotentialAc(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotentialAc + /// + public static ElectricPotentialAc MinValue => new ElectricPotentialAc(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotentialAc; + + /// + /// All units of measurement for the ElectricPotentialAc quantity. + /// + public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. + /// + public static ElectricPotentialAc Zero => new ElectricPotentialAc(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialAc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotentialAc in KilovoltsAc. + /// + public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); + + /// + /// Get ElectricPotentialAc in MegavoltsAc. + /// + public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); + + /// + /// Get ElectricPotentialAc in MicrovoltsAc. + /// + public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); + + /// + /// Get ElectricPotentialAc in MillivoltsAc. + /// + public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); + + /// + /// Get ElectricPotentialAc in VoltsAc. + /// + public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); + + #endregion + + #region Static Methods + /// - /// Get nullable ElectricPotentialAc from nullable MicrovoltsAc. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialAc? FromMicrovoltsAc(QuantityValue? microvoltsac) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialAcUnit unit) { - return microvoltsac.HasValue ? FromMicrovoltsAc(microvoltsac.Value) : default(ElectricPotentialAc?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricPotentialAc from nullable MillivoltsAc. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialAc? FromMillivoltsAc(QuantityValue? millivoltsac) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider) { - return millivoltsac.HasValue ? FromMillivoltsAc(millivoltsac.Value) : default(ElectricPotentialAc?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialAc from KilovoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) + { + double value = (double) kilovoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); + } + /// + /// Get ElectricPotentialAc from MegavoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) + { + double value = (double) megavoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); + } + /// + /// Get ElectricPotentialAc from MicrovoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) + { + double value = (double) microvoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); + } + /// + /// Get ElectricPotentialAc from MillivoltsAc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) + { + double value = (double) millivoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); + } /// - /// Get nullable ElectricPotentialAc from nullable VoltsAc. + /// Get ElectricPotentialAc from VoltsAc. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialAc? FromVoltsAc(QuantityValue? voltsac) + /// If value is NaN or Infinity. + public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) { - return voltsac.HasValue ? FromVoltsAc(voltsac.Value) : default(ElectricPotentialAc?); + double value = (double) voltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); } /// @@ -113,28 +253,156 @@ public partial struct ElectricPotentialAc : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricPotentialAc unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialAc? From(QuantityValue? value, ElectricPotentialAcUnit fromUnit) + public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) { - return value.HasValue ? new ElectricPotentialAc((double)value.Value, fromUnit) : default(ElectricPotentialAc?); + return new ElectricPotentialAc((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotentialAc Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialAc result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricPotentialAcUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricPotentialAcUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricPotentialAc operator -(ElectricPotentialAc right) @@ -174,6 +442,8 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(ElectricPotentialAc left, ElectricPotentialAc right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +464,224 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialAc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) + public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Equals(right); + } + + public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialAc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(ElectricPotentialAc other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialAc Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialAcUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsAc(x.VoltsAc + y.VoltsAc)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialAc result) + /// A hash code for the current ElectricPotentialAc. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricPotentialAc); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialAcUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricPotentialAc with the specified unit. + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotentialAc(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricPotentialAcUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialAcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs index d822bced9f..8e52d3a11f 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,202 @@ namespace UnitsNet /// /// The Electric Potential of a system known to use Direct Current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricPotentialDc : IComparable, IComparable + public partial struct ElectricPotentialDc : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ElectricPotentialDc from nullable KilovoltsDc. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialDc? FromKilovoltsDc(QuantityValue? kilovoltsdc) + private readonly ElectricPotentialDcUnit? _unit; + + static ElectricPotentialDc() { - return kilovoltsdc.HasValue ? FromKilovoltsDc(kilovoltsdc.Value) : default(ElectricPotentialDc?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable ElectricPotentialDc from nullable MegavoltsDc. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialDc? FromMegavoltsDc(QuantityValue? megavoltsdc) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricPotentialDc(double numericValue, ElectricPotentialDcUnit unit) { - return megavoltsdc.HasValue ? FromMegavoltsDc(megavoltsdc.Value) : default(ElectricPotentialDc?); + if(unit == ElectricPotentialDcUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. + /// + public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; + + /// + /// Represents the largest possible value of ElectricPotentialDc + /// + public static ElectricPotentialDc MaxValue => new ElectricPotentialDc(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricPotentialDc + /// + public static ElectricPotentialDc MinValue => new ElectricPotentialDc(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricPotentialDc; + + /// + /// All units of measurement for the ElectricPotentialDc quantity. + /// + public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. + /// + public static ElectricPotentialDc Zero => new ElectricPotentialDc(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricPotentialDc.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricPotentialDc in KilovoltsDc. + /// + public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); + + /// + /// Get ElectricPotentialDc in MegavoltsDc. + /// + public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); + + /// + /// Get ElectricPotentialDc in MicrovoltsDc. + /// + public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); + + /// + /// Get ElectricPotentialDc in MillivoltsDc. + /// + public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); + + /// + /// Get ElectricPotentialDc in VoltsDc. + /// + public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); + + #endregion + + #region Static Methods + /// - /// Get nullable ElectricPotentialDc from nullable MicrovoltsDc. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialDc? FromMicrovoltsDc(QuantityValue? microvoltsdc) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricPotentialDcUnit unit) { - return microvoltsdc.HasValue ? FromMicrovoltsDc(microvoltsdc.Value) : default(ElectricPotentialDc?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricPotentialDc from nullable MillivoltsDc. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialDc? FromMillivoltsDc(QuantityValue? millivoltsdc) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider) { - return millivoltsdc.HasValue ? FromMillivoltsDc(millivoltsdc.Value) : default(ElectricPotentialDc?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricPotentialDc from KilovoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) + { + double value = (double) kilovoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); + } + /// + /// Get ElectricPotentialDc from MegavoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) + { + double value = (double) megavoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); + } + /// + /// Get ElectricPotentialDc from MicrovoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) + { + double value = (double) microvoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); + } + /// + /// Get ElectricPotentialDc from MillivoltsDc. + /// + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) + { + double value = (double) millivoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); + } /// - /// Get nullable ElectricPotentialDc from nullable VoltsDc. + /// Get ElectricPotentialDc from VoltsDc. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricPotentialDc? FromVoltsDc(QuantityValue? voltsdc) + /// If value is NaN or Infinity. + public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) { - return voltsdc.HasValue ? FromVoltsDc(voltsdc.Value) : default(ElectricPotentialDc?); + double value = (double) voltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); } /// @@ -113,28 +253,156 @@ public partial struct ElectricPotentialDc : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricPotentialDc unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricPotentialDc? From(QuantityValue? value, ElectricPotentialDcUnit fromUnit) + public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) { - return value.HasValue ? new ElectricPotentialDc((double)value.Value, fromUnit) : default(ElectricPotentialDc?); + return new ElectricPotentialDc((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotentialDc Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialDc result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricPotentialDcUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricPotentialDcUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricPotentialDc operator -(ElectricPotentialDc right) @@ -174,6 +442,8 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(ElectricPotentialDc left, ElectricPotentialDc right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +464,224 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialDc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) + public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Equals(right); + } + + public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricPotentialDc, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(ElectricPotentialDc other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialDc Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricPotentialDcUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltsDc(x.VoltsDc + y.VoltsDc)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialDc result) + /// A hash code for the current ElectricPotentialDc. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricPotentialDc); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialDcUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricPotentialDc with the specified unit. + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricPotentialDc(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricPotentialDcUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialDcUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs index c7475f3f10..62a484bcd7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,202 @@ namespace UnitsNet /// /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricResistance : IComparable, IComparable + public partial struct ElectricResistance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ElectricResistance from nullable Gigaohms. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistance? FromGigaohms(QuantityValue? gigaohms) + private readonly ElectricResistanceUnit? _unit; + + static ElectricResistance() { - return gigaohms.HasValue ? FromGigaohms(gigaohms.Value) : default(ElectricResistance?); + BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); } /// - /// Get nullable ElectricResistance from nullable Kiloohms. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistance? FromKiloohms(QuantityValue? kiloohms) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricResistance(double numericValue, ElectricResistanceUnit unit) { - return kiloohms.HasValue ? FromKiloohms(kiloohms.Value) : default(ElectricResistance?); + if(unit == ElectricResistanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. + /// + public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; + + /// + /// Represents the largest possible value of ElectricResistance + /// + public static ElectricResistance MaxValue => new ElectricResistance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ElectricResistance + /// + public static ElectricResistance MinValue => new ElectricResistance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricResistance; + + /// + /// All units of measurement for the ElectricResistance quantity. + /// + public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. + /// + public static ElectricResistance Zero => new ElectricResistance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricResistance in Gigaohms. + /// + public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); + + /// + /// Get ElectricResistance in Kiloohms. + /// + public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); + + /// + /// Get ElectricResistance in Megaohms. + /// + public double Megaohms => As(ElectricResistanceUnit.Megaohm); + + /// + /// Get ElectricResistance in Milliohms. + /// + public double Milliohms => As(ElectricResistanceUnit.Milliohm); + + /// + /// Get ElectricResistance in Ohms. + /// + public double Ohms => As(ElectricResistanceUnit.Ohm); + + #endregion + + #region Static Methods + /// - /// Get nullable ElectricResistance from nullable Megaohms. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistance? FromMegaohms(QuantityValue? megaohms) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistanceUnit unit) { - return megaohms.HasValue ? FromMegaohms(megaohms.Value) : default(ElectricResistance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricResistance from nullable Milliohms. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistance? FromMilliohms(QuantityValue? milliohms) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider) { - return milliohms.HasValue ? FromMilliohms(milliohms.Value) : default(ElectricResistance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistance from Gigaohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromGigaohms(QuantityValue gigaohms) + { + double value = (double) gigaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); + } + /// + /// Get ElectricResistance from Kiloohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromKiloohms(QuantityValue kiloohms) + { + double value = (double) kiloohms; + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); + } + /// + /// Get ElectricResistance from Megaohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromMegaohms(QuantityValue megaohms) + { + double value = (double) megaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); + } + /// + /// Get ElectricResistance from Milliohms. + /// + /// If value is NaN or Infinity. + public static ElectricResistance FromMilliohms(QuantityValue milliohms) + { + double value = (double) milliohms; + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); + } /// - /// Get nullable ElectricResistance from nullable Ohms. + /// Get ElectricResistance from Ohms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistance? FromOhms(QuantityValue? ohms) + /// If value is NaN or Infinity. + public static ElectricResistance FromOhms(QuantityValue ohms) { - return ohms.HasValue ? FromOhms(ohms.Value) : default(ElectricResistance?); + double value = (double) ohms; + return new ElectricResistance(value, ElectricResistanceUnit.Ohm); } /// @@ -113,28 +253,156 @@ public partial struct ElectricResistance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricResistance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistance? From(QuantityValue? value, ElectricResistanceUnit fromUnit) + public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) { - return value.HasValue ? new ElectricResistance((double)value.Value, fromUnit) : default(ElectricResistance?); + return new ElectricResistance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricResistance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricResistanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricResistanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricResistance operator -(ElectricResistance right) @@ -174,6 +442,8 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] IF #endregion + #region Equality / IComparable + public static bool operator <=(ElectricResistance left, ElectricResistance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +464,224 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] IF return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricResistance left, ElectricResistance right) + public static bool operator ==(ElectricResistance left, ElectricResistance right) + { + return left.Equals(right); + } + + public static bool operator !=(ElectricResistance left, ElectricResistance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricResistance left, ElectricResistance right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(ElectricResistance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricResistanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromOhms(x.Ohms + y.Ohms)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistance result) + /// A hash code for the current ElectricResistance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricResistance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricResistance to another ElectricResistance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricResistance with the specified unit. + public ElectricResistance ToUnit(ElectricResistanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricResistance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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.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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricResistanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricResistanceUnit.Gigaohm: return (baseUnitValue) / 1e9d; + case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; + case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; + case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; + case ElectricResistanceUnit.Ohm: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs index 0a51225cdb..9a5659af14 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,191 @@ namespace UnitsNet /// /// Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ElectricResistivity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// + public partial struct ElectricResistivity : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricResistivityUnit? _unit; + + static ElectricResistivity() + { + BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); + } /// - /// Get nullable ElectricResistivity from nullable MicroohmMeters. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistivity? FromMicroohmMeters(QuantityValue? microohmmeters) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ElectricResistivity(double numericValue, ElectricResistivityUnit unit) { - return microohmmeters.HasValue ? FromMicroohmMeters(microohmmeters.Value) : default(ElectricResistivity?); + if(unit == ElectricResistivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. + /// + public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; + + /// + /// Represents the largest possible value of ElectricResistivity + /// + public static ElectricResistivity MaxValue => new ElectricResistivity(double.MaxValue, BaseUnit); + /// - /// Get nullable ElectricResistivity from nullable MilliohmMeters. + /// Represents the smallest possible value of ElectricResistivity /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistivity? FromMilliohmMeters(QuantityValue? milliohmmeters) + public static ElectricResistivity MinValue => new ElectricResistivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ElectricResistivity; + + /// + /// All units of measurement for the ElectricResistivity quantity. + /// + public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. + /// + public static ElectricResistivity Zero => new ElectricResistivity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ElectricResistivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ElectricResistivity in MicroohmMeters. + /// + public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); + + /// + /// Get ElectricResistivity in MilliohmMeters. + /// + public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); + + /// + /// Get ElectricResistivity in NanoohmMeters. + /// + public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); + + /// + /// Get ElectricResistivity in OhmMeters. + /// + public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ElectricResistivityUnit unit) { - return milliohmmeters.HasValue ? FromMilliohmMeters(milliohmmeters.Value) : default(ElectricResistivity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ElectricResistivity from nullable NanoohmMeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistivity? FromNanoohmMeters(QuantityValue? nanoohmmeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider) { - return nanoohmmeters.HasValue ? FromNanoohmMeters(nanoohmmeters.Value) : default(ElectricResistivity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ElectricResistivity from MicroohmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) + { + double value = (double) microohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); + } + /// + /// Get ElectricResistivity from MilliohmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) + { + double value = (double) milliohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); + } /// - /// Get nullable ElectricResistivity from nullable OhmMeters. + /// Get ElectricResistivity from NanoohmMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ElectricResistivity? FromOhmMeters(QuantityValue? ohmmeters) + /// If value is NaN or Infinity. + public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) { - return ohmmeters.HasValue ? FromOhmMeters(ohmmeters.Value) : default(ElectricResistivity?); + double value = (double) nanoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); + } + /// + /// Get ElectricResistivity from OhmMeters. + /// + /// If value is NaN or Infinity. + public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) + { + double value = (double) ohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); } /// @@ -104,28 +242,156 @@ public partial struct ElectricResistivity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ElectricResistivity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ElectricResistivity? From(QuantityValue? value, ElectricResistivityUnit fromUnit) + public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) { - return value.HasValue ? new ElectricResistivity((double)value.Value, fromUnit) : default(ElectricResistivity?); + return new ElectricResistivity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricResistivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ElectricResistivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ElectricResistivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricResistivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ElectricResistivity operator -(ElectricResistivity right) @@ -165,6 +431,8 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(ElectricResistivity left, ElectricResistivity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +453,222 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ElectricResistivity left, ElectricResistivity right) + public static bool operator ==(ElectricResistivity left, ElectricResistivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ElectricResistivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ElectricResistivity left, ElectricResistivity right) + public static bool operator !=(ElectricResistivity left, ElectricResistivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ElectricResistivity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistivity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ElectricResistivity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ElectricResistivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromOhmMeters(x.OhmMeters + y.OhmMeters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistivity result) + /// A hash code for the current ElectricResistivity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ElectricResistivity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ElectricResistivity with the specified unit. + public ElectricResistivity ToUnit(ElectricResistivityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ElectricResistivity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; + case ElectricResistivityUnit.OhmMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ElectricResistivityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ElectricResistivityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; + case ElectricResistivityUnit.OhmMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs index 7a3e92b922..70dd0022b9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,213 +49,440 @@ namespace UnitsNet /// /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Energy : IComparable, IComparable + public partial struct Energy : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Energy from nullable BritishThermalUnits. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromBritishThermalUnits(QuantityValue? britishthermalunits) + private readonly EnergyUnit? _unit; + + static Energy() { - return britishthermalunits.HasValue ? FromBritishThermalUnits(britishthermalunits.Value) : default(Energy?); + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable Energy from nullable Calories. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromCalories(QuantityValue? calories) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Energy(double numericValue, EnergyUnit unit) { - return calories.HasValue ? FromCalories(calories.Value) : default(Energy?); + if(unit == EnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Energy, which is Joule. All conversions go via this value. + /// + public static EnergyUnit BaseUnit => EnergyUnit.Joule; + + /// + /// Represents the largest possible value of Energy + /// + public static Energy MaxValue => new Energy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Energy + /// + public static Energy MinValue => new Energy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Energy; + + /// + /// All units of measurement for the Energy quantity. + /// + public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Joule. + /// + public static Energy Zero => new Energy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Energy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Energy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Energy in BritishThermalUnits. + /// + public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); + + /// + /// Get Energy in Calories. + /// + public double Calories => As(EnergyUnit.Calorie); + + /// + /// Get Energy in DecathermsEc. + /// + public double DecathermsEc => As(EnergyUnit.DecathermEc); + + /// + /// Get Energy in DecathermsImperial. + /// + public double DecathermsImperial => As(EnergyUnit.DecathermImperial); + + /// + /// Get Energy in DecathermsUs. + /// + public double DecathermsUs => As(EnergyUnit.DecathermUs); + + /// + /// Get Energy in ElectronVolts. + /// + public double ElectronVolts => As(EnergyUnit.ElectronVolt); + + /// + /// Get Energy in Ergs. + /// + public double Ergs => As(EnergyUnit.Erg); + + /// + /// Get Energy in FootPounds. + /// + public double FootPounds => As(EnergyUnit.FootPound); + + /// + /// Get Energy in GigabritishThermalUnits. + /// + public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); + + /// + /// Get Energy in GigawattHours. + /// + public double GigawattHours => As(EnergyUnit.GigawattHour); + + /// + /// Get Energy in Joules. + /// + public double Joules => As(EnergyUnit.Joule); + + /// + /// Get Energy in KilobritishThermalUnits. + /// + public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); + + /// + /// Get Energy in Kilocalories. + /// + public double Kilocalories => As(EnergyUnit.Kilocalorie); + + /// + /// Get Energy in Kilojoules. + /// + public double Kilojoules => As(EnergyUnit.Kilojoule); + /// - /// Get nullable Energy from nullable DecathermsEc. + /// Get Energy in KilowattHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromDecathermsEc(QuantityValue? decathermsec) + public double KilowattHours => As(EnergyUnit.KilowattHour); + + /// + /// Get Energy in MegabritishThermalUnits. + /// + public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); + + /// + /// Get Energy in Megajoules. + /// + public double Megajoules => As(EnergyUnit.Megajoule); + + /// + /// Get Energy in MegawattHours. + /// + public double MegawattHours => As(EnergyUnit.MegawattHour); + + /// + /// Get Energy in ThermsEc. + /// + public double ThermsEc => As(EnergyUnit.ThermEc); + + /// + /// Get Energy in ThermsImperial. + /// + public double ThermsImperial => As(EnergyUnit.ThermImperial); + + /// + /// Get Energy in ThermsUs. + /// + public double ThermsUs => As(EnergyUnit.ThermUs); + + /// + /// Get Energy in WattHours. + /// + public double WattHours => As(EnergyUnit.WattHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EnergyUnit unit) { - return decathermsec.HasValue ? FromDecathermsEc(decathermsec.Value) : default(Energy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Energy from nullable DecathermsImperial. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromDecathermsImperial(QuantityValue? decathermsimperial) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] IFormatProvider provider) { - return decathermsimperial.HasValue ? FromDecathermsImperial(decathermsimperial.Value) : default(Energy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Energy from nullable DecathermsUs. + /// Get Energy from BritishThermalUnits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromDecathermsUs(QuantityValue? decathermsus) + /// If value is NaN or Infinity. + public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) { - return decathermsus.HasValue ? FromDecathermsUs(decathermsus.Value) : default(Energy?); + double value = (double) britishthermalunits; + return new Energy(value, EnergyUnit.BritishThermalUnit); } - /// - /// Get nullable Energy from nullable ElectronVolts. + /// Get Energy from Calories. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromElectronVolts(QuantityValue? electronvolts) + /// If value is NaN or Infinity. + public static Energy FromCalories(QuantityValue calories) { - return electronvolts.HasValue ? FromElectronVolts(electronvolts.Value) : default(Energy?); + double value = (double) calories; + return new Energy(value, EnergyUnit.Calorie); } - /// - /// Get nullable Energy from nullable Ergs. + /// Get Energy from DecathermsEc. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromErgs(QuantityValue? ergs) + /// If value is NaN or Infinity. + public static Energy FromDecathermsEc(QuantityValue decathermsec) { - return ergs.HasValue ? FromErgs(ergs.Value) : default(Energy?); + double value = (double) decathermsec; + return new Energy(value, EnergyUnit.DecathermEc); } - /// - /// Get nullable Energy from nullable FootPounds. + /// Get Energy from DecathermsImperial. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromFootPounds(QuantityValue? footpounds) + /// If value is NaN or Infinity. + public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) { - return footpounds.HasValue ? FromFootPounds(footpounds.Value) : default(Energy?); + double value = (double) decathermsimperial; + return new Energy(value, EnergyUnit.DecathermImperial); } - /// - /// Get nullable Energy from nullable GigabritishThermalUnits. + /// Get Energy from DecathermsUs. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromGigabritishThermalUnits(QuantityValue? gigabritishthermalunits) + /// If value is NaN or Infinity. + public static Energy FromDecathermsUs(QuantityValue decathermsus) { - return gigabritishthermalunits.HasValue ? FromGigabritishThermalUnits(gigabritishthermalunits.Value) : default(Energy?); + double value = (double) decathermsus; + return new Energy(value, EnergyUnit.DecathermUs); } - /// - /// Get nullable Energy from nullable GigawattHours. + /// Get Energy from ElectronVolts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromGigawattHours(QuantityValue? gigawatthours) + /// If value is NaN or Infinity. + public static Energy FromElectronVolts(QuantityValue electronvolts) { - return gigawatthours.HasValue ? FromGigawattHours(gigawatthours.Value) : default(Energy?); + double value = (double) electronvolts; + return new Energy(value, EnergyUnit.ElectronVolt); } - /// - /// Get nullable Energy from nullable Joules. + /// Get Energy from Ergs. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromJoules(QuantityValue? joules) + /// If value is NaN or Infinity. + public static Energy FromErgs(QuantityValue ergs) { - return joules.HasValue ? FromJoules(joules.Value) : default(Energy?); + double value = (double) ergs; + return new Energy(value, EnergyUnit.Erg); } - /// - /// Get nullable Energy from nullable KilobritishThermalUnits. + /// Get Energy from FootPounds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromKilobritishThermalUnits(QuantityValue? kilobritishthermalunits) + /// If value is NaN or Infinity. + public static Energy FromFootPounds(QuantityValue footpounds) { - return kilobritishthermalunits.HasValue ? FromKilobritishThermalUnits(kilobritishthermalunits.Value) : default(Energy?); + double value = (double) footpounds; + return new Energy(value, EnergyUnit.FootPound); } - /// - /// Get nullable Energy from nullable Kilocalories. + /// Get Energy from GigabritishThermalUnits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromKilocalories(QuantityValue? kilocalories) + /// If value is NaN or Infinity. + public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) { - return kilocalories.HasValue ? FromKilocalories(kilocalories.Value) : default(Energy?); + double value = (double) gigabritishthermalunits; + return new Energy(value, EnergyUnit.GigabritishThermalUnit); } - /// - /// Get nullable Energy from nullable Kilojoules. + /// Get Energy from GigawattHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromKilojoules(QuantityValue? kilojoules) + /// If value is NaN or Infinity. + public static Energy FromGigawattHours(QuantityValue gigawatthours) { - return kilojoules.HasValue ? FromKilojoules(kilojoules.Value) : default(Energy?); + double value = (double) gigawatthours; + return new Energy(value, EnergyUnit.GigawattHour); } - /// - /// Get nullable Energy from nullable KilowattHours. + /// Get Energy from Joules. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromKilowattHours(QuantityValue? kilowatthours) + /// If value is NaN or Infinity. + public static Energy FromJoules(QuantityValue joules) { - return kilowatthours.HasValue ? FromKilowattHours(kilowatthours.Value) : default(Energy?); + double value = (double) joules; + return new Energy(value, EnergyUnit.Joule); } - /// - /// Get nullable Energy from nullable MegabritishThermalUnits. + /// Get Energy from KilobritishThermalUnits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromMegabritishThermalUnits(QuantityValue? megabritishthermalunits) + /// If value is NaN or Infinity. + public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) { - return megabritishthermalunits.HasValue ? FromMegabritishThermalUnits(megabritishthermalunits.Value) : default(Energy?); + double value = (double) kilobritishthermalunits; + return new Energy(value, EnergyUnit.KilobritishThermalUnit); } - /// - /// Get nullable Energy from nullable Megajoules. + /// Get Energy from Kilocalories. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromMegajoules(QuantityValue? megajoules) + /// If value is NaN or Infinity. + public static Energy FromKilocalories(QuantityValue kilocalories) { - return megajoules.HasValue ? FromMegajoules(megajoules.Value) : default(Energy?); + double value = (double) kilocalories; + return new Energy(value, EnergyUnit.Kilocalorie); } - /// - /// Get nullable Energy from nullable MegawattHours. + /// Get Energy from Kilojoules. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromMegawattHours(QuantityValue? megawatthours) + /// If value is NaN or Infinity. + public static Energy FromKilojoules(QuantityValue kilojoules) { - return megawatthours.HasValue ? FromMegawattHours(megawatthours.Value) : default(Energy?); + double value = (double) kilojoules; + return new Energy(value, EnergyUnit.Kilojoule); } - /// - /// Get nullable Energy from nullable ThermsEc. + /// Get Energy from KilowattHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromThermsEc(QuantityValue? thermsec) + /// If value is NaN or Infinity. + public static Energy FromKilowattHours(QuantityValue kilowatthours) { - return thermsec.HasValue ? FromThermsEc(thermsec.Value) : default(Energy?); + double value = (double) kilowatthours; + return new Energy(value, EnergyUnit.KilowattHour); } - /// - /// Get nullable Energy from nullable ThermsImperial. + /// Get Energy from MegabritishThermalUnits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromThermsImperial(QuantityValue? thermsimperial) + /// If value is NaN or Infinity. + public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) { - return thermsimperial.HasValue ? FromThermsImperial(thermsimperial.Value) : default(Energy?); + double value = (double) megabritishthermalunits; + return new Energy(value, EnergyUnit.MegabritishThermalUnit); } - /// - /// Get nullable Energy from nullable ThermsUs. + /// Get Energy from Megajoules. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromThermsUs(QuantityValue? thermsus) + /// If value is NaN or Infinity. + public static Energy FromMegajoules(QuantityValue megajoules) { - return thermsus.HasValue ? FromThermsUs(thermsus.Value) : default(Energy?); + double value = (double) megajoules; + return new Energy(value, EnergyUnit.Megajoule); + } + /// + /// Get Energy from MegawattHours. + /// + /// If value is NaN or Infinity. + public static Energy FromMegawattHours(QuantityValue megawatthours) + { + double value = (double) megawatthours; + return new Energy(value, EnergyUnit.MegawattHour); + } + /// + /// Get Energy from ThermsEc. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsEc(QuantityValue thermsec) + { + double value = (double) thermsec; + return new Energy(value, EnergyUnit.ThermEc); + } + /// + /// Get Energy from ThermsImperial. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsImperial(QuantityValue thermsimperial) + { + double value = (double) thermsimperial; + return new Energy(value, EnergyUnit.ThermImperial); + } + /// + /// Get Energy from ThermsUs. + /// + /// If value is NaN or Infinity. + public static Energy FromThermsUs(QuantityValue thermsus) + { + double value = (double) thermsus; + return new Energy(value, EnergyUnit.ThermUs); } - /// - /// Get nullable Energy from nullable WattHours. + /// Get Energy from WattHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Energy? FromWattHours(QuantityValue? watthours) + /// If value is NaN or Infinity. + public static Energy FromWattHours(QuantityValue watthours) { - return watthours.HasValue ? FromWattHours(watthours.Value) : default(Energy?); + double value = (double) watthours; + return new Energy(value, EnergyUnit.WattHour); } /// @@ -266,28 +491,156 @@ public partial struct Energy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Energy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Energy? From(QuantityValue? value, EnergyUnit fromUnit) + public static Energy From(QuantityValue value, EnergyUnit fromUnit) { - return value.HasValue ? new Energy((double)value.Value, fromUnit) : default(Energy?); + return new Energy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Energy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Energy result) + { + return TryParse(str, null, out result); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Energy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static EnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static EnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out EnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Energy operator -(Energy right) @@ -327,6 +680,8 @@ public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] IFormatProvide #endregion + #region Equality / IComparable + public static bool operator <=(Energy left, Energy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -347,180 +702,258 @@ public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] IFormatProvide return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Energy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Energy left, Energy right) + public static bool operator ==(Energy left, Energy right) + { + return left.Equals(right); + } + + public static bool operator !=(Energy left, Energy right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Energy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Energy left, Energy right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Energy other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Energy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Energy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - EnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoules(x.Joules + y.Joules)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Energy result) + /// A hash code for the current Energy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Energy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Energy to another Energy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Energy with the specified unit. + public Energy ToUnit(EnergyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Energy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; + case EnergyUnit.Calorie: return _value*4.184; + case EnergyUnit.DecathermEc: return (_value*1.05505585262e8) * 1e1d; + case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e8) * 1e1d; + case EnergyUnit.DecathermUs: return (_value*1.054804e8) * 1e1d; + case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; + case EnergyUnit.Erg: return _value*1e-7; + case EnergyUnit.FootPound: return _value*1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; + case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; + case EnergyUnit.Joule: return _value; + case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; + case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; + case EnergyUnit.Kilojoule: return (_value) * 1e3d; + case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; + case EnergyUnit.Megajoule: return (_value) * 1e6d; + case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; + case EnergyUnit.ThermEc: return _value*1.05505585262e8; + case EnergyUnit.ThermImperial: return _value*1.05505585257348e8; + case EnergyUnit.ThermUs: return _value*1.054804e8; + case EnergyUnit.WattHour: return _value*3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(EnergyUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == EnergyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; + case EnergyUnit.Calorie: return baseUnitValue/4.184; + case EnergyUnit.DecathermEc: return (baseUnitValue/1.05505585262e8) / 1e1d; + case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e8) / 1e1d; + case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e8) / 1e1d; + case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; + case EnergyUnit.Erg: return baseUnitValue/1e-7; + case EnergyUnit.FootPound: return baseUnitValue/1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; + case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; + case EnergyUnit.Joule: return baseUnitValue; + case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; + case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; + case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; + case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; + case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; + case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; + case EnergyUnit.ThermEc: return baseUnitValue/1.05505585262e8; + case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e8; + case EnergyUnit.ThermUs: return baseUnitValue/1.054804e8; + case EnergyUnit.WattHour: return baseUnitValue/3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(EnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs index c86468e24e..d70b0e10ea 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,78 +49,230 @@ namespace UnitsNet /// /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Entropy : IComparable, IComparable + public partial struct Entropy : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Entropy from nullable CaloriesPerKelvin. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromCaloriesPerKelvin(QuantityValue? caloriesperkelvin) + private readonly EntropyUnit? _unit; + + static Entropy() { - return caloriesperkelvin.HasValue ? FromCaloriesPerKelvin(caloriesperkelvin.Value) : default(Entropy?); + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); } /// - /// Get nullable Entropy from nullable JoulesPerDegreeCelsius. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromJoulesPerDegreeCelsius(QuantityValue? joulesperdegreecelsius) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Entropy(double numericValue, EntropyUnit unit) { - return joulesperdegreecelsius.HasValue ? FromJoulesPerDegreeCelsius(joulesperdegreecelsius.Value) : default(Entropy?); + if(unit == EntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. + /// + public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; + + /// + /// Represents the largest possible value of Entropy + /// + public static Entropy MaxValue => new Entropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Entropy + /// + public static Entropy MinValue => new Entropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Entropy; + + /// + /// All units of measurement for the Entropy quantity. + /// + public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. + /// + public static Entropy Zero => new Entropy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Entropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Entropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Entropy in CaloriesPerKelvin. + /// + public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); + + /// + /// Get Entropy in JoulesPerDegreeCelsius. + /// + public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); + + /// + /// Get Entropy in JoulesPerKelvin. + /// + public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); + /// - /// Get nullable Entropy from nullable JoulesPerKelvin. + /// Get Entropy in KilocaloriesPerKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromJoulesPerKelvin(QuantityValue? joulesperkelvin) + public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); + + /// + /// Get Entropy in KilojoulesPerDegreeCelsius. + /// + public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); + + /// + /// Get Entropy in KilojoulesPerKelvin. + /// + public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); + + /// + /// Get Entropy in MegajoulesPerKelvin. + /// + public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(EntropyUnit unit) { - return joulesperkelvin.HasValue ? FromJoulesPerKelvin(joulesperkelvin.Value) : default(Entropy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Entropy from nullable KilocaloriesPerKelvin. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromKilocaloriesPerKelvin(QuantityValue? kilocaloriesperkelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] IFormatProvider provider) { - return kilocaloriesperkelvin.HasValue ? FromKilocaloriesPerKelvin(kilocaloriesperkelvin.Value) : default(Entropy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Entropy from nullable KilojoulesPerDegreeCelsius. + /// Get Entropy from CaloriesPerKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromKilojoulesPerDegreeCelsius(QuantityValue? kilojoulesperdegreecelsius) + /// If value is NaN or Infinity. + public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) { - return kilojoulesperdegreecelsius.HasValue ? FromKilojoulesPerDegreeCelsius(kilojoulesperdegreecelsius.Value) : default(Entropy?); + double value = (double) caloriesperkelvin; + return new Entropy(value, EntropyUnit.CaloriePerKelvin); } - /// - /// Get nullable Entropy from nullable KilojoulesPerKelvin. + /// Get Entropy from JoulesPerDegreeCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromKilojoulesPerKelvin(QuantityValue? kilojoulesperkelvin) + /// If value is NaN or Infinity. + public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) { - return kilojoulesperkelvin.HasValue ? FromKilojoulesPerKelvin(kilojoulesperkelvin.Value) : default(Entropy?); + double value = (double) joulesperdegreecelsius; + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); } - /// - /// Get nullable Entropy from nullable MegajoulesPerKelvin. + /// Get Entropy from JoulesPerKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Entropy? FromMegajoulesPerKelvin(QuantityValue? megajoulesperkelvin) + /// If value is NaN or Infinity. + public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) { - return megajoulesperkelvin.HasValue ? FromMegajoulesPerKelvin(megajoulesperkelvin.Value) : default(Entropy?); + double value = (double) joulesperkelvin; + return new Entropy(value, EntropyUnit.JoulePerKelvin); + } + /// + /// Get Entropy from KilocaloriesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) + { + double value = (double) kilocaloriesperkelvin; + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); + } + /// + /// Get Entropy from KilojoulesPerDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) + { + double value = (double) kilojoulesperdegreecelsius; + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); + } + /// + /// Get Entropy from KilojoulesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) + { + double value = (double) kilojoulesperkelvin; + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); + } + /// + /// Get Entropy from MegajoulesPerKelvin. + /// + /// If value is NaN or Infinity. + public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) + { + double value = (double) megajoulesperkelvin; + return new Entropy(value, EntropyUnit.MegajoulePerKelvin); } /// @@ -131,28 +281,156 @@ public partial struct Entropy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Entropy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Entropy? From(QuantityValue? value, EntropyUnit fromUnit) + public static Entropy From(QuantityValue value, EntropyUnit fromUnit) { - return value.HasValue ? new Entropy((double)value.Value, fromUnit) : default(Entropy?); + return new Entropy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Entropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Entropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Entropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static EntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static EntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out EntropyUnit unit) + { + return TryParseUnit(str, null, out unit); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out EntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Entropy operator -(Entropy right) @@ -192,6 +470,8 @@ public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] IFormatProvid #endregion + #region Equality / IComparable + public static bool operator <=(Entropy left, Entropy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -212,180 +492,228 @@ public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] IFormatProvid return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Entropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Entropy left, Entropy right) + public static bool operator ==(Entropy left, Entropy right) + { + return left.Equals(right); + } + + public static bool operator !=(Entropy left, Entropy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Entropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Entropy left, Entropy right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Entropy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Entropy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Entropy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - EntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKelvin(x.JoulesPerKelvin + y.JoulesPerKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Entropy result) + /// A hash code for the current Entropy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Entropy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Entropy to another Entropy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Entropy with the specified unit. + public Entropy ToUnit(EntropyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Entropy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == EntropyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(EntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Flow.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Flow.NetFramework.g.cs deleted file mode 100644 index a7be3c7a7f..0000000000 --- a/UnitsNet/GeneratedCode/Quantities/Flow.NetFramework.g.cs +++ /dev/null @@ -1,544 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Flow : IComparable, IComparable - { - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - - #region Nullable From Methods - - /// - /// Get nullable Flow from nullable CentilitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCentilitersPerMinute(QuantityValue? centilitersperminute) - { - return centilitersperminute.HasValue ? FromCentilitersPerMinute(centilitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicDecimetersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicDecimetersPerMinute(QuantityValue? cubicdecimetersperminute) - { - return cubicdecimetersperminute.HasValue ? FromCubicDecimetersPerMinute(cubicdecimetersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicFeetPerHour. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicFeetPerHour(QuantityValue? cubicfeetperhour) - { - return cubicfeetperhour.HasValue ? FromCubicFeetPerHour(cubicfeetperhour.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicFeetPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicFeetPerMinute(QuantityValue? cubicfeetperminute) - { - return cubicfeetperminute.HasValue ? FromCubicFeetPerMinute(cubicfeetperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicFeetPerSecond. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicFeetPerSecond(QuantityValue? cubicfeetpersecond) - { - return cubicfeetpersecond.HasValue ? FromCubicFeetPerSecond(cubicfeetpersecond.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicMetersPerHour. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicMetersPerHour(QuantityValue? cubicmetersperhour) - { - return cubicmetersperhour.HasValue ? FromCubicMetersPerHour(cubicmetersperhour.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicMetersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicMetersPerMinute(QuantityValue? cubicmetersperminute) - { - return cubicmetersperminute.HasValue ? FromCubicMetersPerMinute(cubicmetersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicMetersPerSecond. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicMetersPerSecond(QuantityValue? cubicmeterspersecond) - { - return cubicmeterspersecond.HasValue ? FromCubicMetersPerSecond(cubicmeterspersecond.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicYardsPerHour. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicYardsPerHour(QuantityValue? cubicyardsperhour) - { - return cubicyardsperhour.HasValue ? FromCubicYardsPerHour(cubicyardsperhour.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicYardsPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicYardsPerMinute(QuantityValue? cubicyardsperminute) - { - return cubicyardsperminute.HasValue ? FromCubicYardsPerMinute(cubicyardsperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable CubicYardsPerSecond. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromCubicYardsPerSecond(QuantityValue? cubicyardspersecond) - { - return cubicyardspersecond.HasValue ? FromCubicYardsPerSecond(cubicyardspersecond.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable DecilitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromDecilitersPerMinute(QuantityValue? decilitersperminute) - { - return decilitersperminute.HasValue ? FromDecilitersPerMinute(decilitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable KilolitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromKilolitersPerMinute(QuantityValue? kilolitersperminute) - { - return kilolitersperminute.HasValue ? FromKilolitersPerMinute(kilolitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable LitersPerHour. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromLitersPerHour(QuantityValue? litersperhour) - { - return litersperhour.HasValue ? FromLitersPerHour(litersperhour.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable LitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromLitersPerMinute(QuantityValue? litersperminute) - { - return litersperminute.HasValue ? FromLitersPerMinute(litersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable LitersPerSecond. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromLitersPerSecond(QuantityValue? literspersecond) - { - return literspersecond.HasValue ? FromLitersPerSecond(literspersecond.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable MicrolitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromMicrolitersPerMinute(QuantityValue? microlitersperminute) - { - return microlitersperminute.HasValue ? FromMicrolitersPerMinute(microlitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable MillilitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromMillilitersPerMinute(QuantityValue? millilitersperminute) - { - return millilitersperminute.HasValue ? FromMillilitersPerMinute(millilitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable MillionUsGallonsPerDay. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromMillionUsGallonsPerDay(QuantityValue? millionusgallonsperday) - { - return millionusgallonsperday.HasValue ? FromMillionUsGallonsPerDay(millionusgallonsperday.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable NanolitersPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromNanolitersPerMinute(QuantityValue? nanolitersperminute) - { - return nanolitersperminute.HasValue ? FromNanolitersPerMinute(nanolitersperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable OilBarrelsPerDay. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromOilBarrelsPerDay(QuantityValue? oilbarrelsperday) - { - return oilbarrelsperday.HasValue ? FromOilBarrelsPerDay(oilbarrelsperday.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable UsGallonsPerHour. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromUsGallonsPerHour(QuantityValue? usgallonsperhour) - { - return usgallonsperhour.HasValue ? FromUsGallonsPerHour(usgallonsperhour.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable UsGallonsPerMinute. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromUsGallonsPerMinute(QuantityValue? usgallonsperminute) - { - return usgallonsperminute.HasValue ? FromUsGallonsPerMinute(usgallonsperminute.Value) : default(Flow?); - } - - /// - /// Get nullable Flow from nullable UsGallonsPerSecond. - /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Flow? FromUsGallonsPerSecond(QuantityValue? usgallonspersecond) - { - return usgallonspersecond.HasValue ? FromUsGallonsPerSecond(usgallonspersecond.Value) : default(Flow?); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Flow unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Flow? From(QuantityValue? value, FlowUnit fromUnit) - { - return value.HasValue ? new Flow((double)value.Value, fromUnit) : default(Flow?); - } - - #endregion - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FlowUnit unit, [CanBeNull] IFormatProvider provider) - { - provider = provider ?? UnitSystem.DefaultCulture; - - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); - } - - #region Arithmetic Operators - - public static Flow operator -(Flow right) - { - return new Flow(-right.Value, right.Unit); - } - - public static Flow operator +(Flow left, Flow right) - { - return new Flow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); - } - - public static Flow operator -(Flow left, Flow right) - { - return new Flow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); - } - - public static Flow operator *(double left, Flow right) - { - return new Flow(left * right.Value, right.Unit); - } - - public static Flow operator *(Flow left, double right) - { - return new Flow(left.Value * right, left.Unit); - } - - public static Flow operator /(Flow left, double right) - { - return new Flow(left.Value / right, left.Unit); - } - - public static double operator /(Flow left, Flow right) - { - return left.CubicMetersPerSecond / right.CubicMetersPerSecond; - } - - #endregion - - public static bool operator <=(Flow left, Flow right) - { - return left.Value <= right.AsBaseNumericType(left.Unit); - } - - public static bool operator >=(Flow left, Flow right) - { - return left.Value >= right.AsBaseNumericType(left.Unit); - } - - public static bool operator <(Flow left, Flow right) - { - return left.Value < right.AsBaseNumericType(left.Unit); - } - - public static bool operator >(Flow left, Flow right) - { - return left.Value > right.AsBaseNumericType(left.Unit); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Flow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Flow left, Flow right) - { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); - } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Flow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Flow left, Flow right) - { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); - } - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Flow Parse(string str, [CanBeNull] IFormatProvider provider) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? UnitSystem.DefaultCulture; - - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - FlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerSecond(x.CubicMetersPerSecond + y.CubicMetersPerSecond)); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Flow result) - { - provider = provider ?? UnitSystem.DefaultCulture; - - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Flow); - return false; - } - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static FlowUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FlowUnit ParseUnit(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); - - if (unit == FlowUnit.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - #endregion - - #region ToString Methods - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . - /// String representation. - public string ToString(FlowUnit unit, [CanBeNull] IFormatProvider provider) - { - return ToString(unit, provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) - { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? UnitSystem.DefaultCulture; - - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - } -} diff --git a/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs index 8546121263..be24f8f69e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,132 +49,314 @@ namespace UnitsNet /// /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Force : IComparable, IComparable + public partial struct Force : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Force from nullable Decanewtons. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromDecanewtons(QuantityValue? decanewtons) + private readonly ForceUnit? _unit; + + static Force() { - return decanewtons.HasValue ? FromDecanewtons(decanewtons.Value) : default(Force?); + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable Force from nullable Dyne. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromDyne(QuantityValue? dyne) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Force(double numericValue, ForceUnit unit) { - return dyne.HasValue ? FromDyne(dyne.Value) : default(Force?); + if(unit == ForceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Force, which is Newton. All conversions go via this value. + /// + public static ForceUnit BaseUnit => ForceUnit.Newton; + + /// + /// Represents the largest possible value of Force + /// + public static Force MaxValue => new Force(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Force + /// + public static Force MinValue => new Force(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Force; + + /// + /// All units of measurement for the Force quantity. + /// + public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Newton. + /// + public static Force Zero => new Force(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Force.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Force.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Force in Decanewtons. + /// + public double Decanewtons => As(ForceUnit.Decanewton); + + /// + /// Get Force in Dyne. + /// + public double Dyne => As(ForceUnit.Dyn); + + /// + /// Get Force in KilogramsForce. + /// + public double KilogramsForce => As(ForceUnit.KilogramForce); + + /// + /// Get Force in Kilonewtons. + /// + public double Kilonewtons => As(ForceUnit.Kilonewton); + + /// + /// Get Force in KiloPonds. + /// + public double KiloPonds => As(ForceUnit.KiloPond); + + /// + /// Get Force in Meganewtons. + /// + public double Meganewtons => As(ForceUnit.Meganewton); + + /// + /// Get Force in Micronewtons. + /// + public double Micronewtons => As(ForceUnit.Micronewton); + + /// + /// Get Force in Millinewtons. + /// + public double Millinewtons => As(ForceUnit.Millinewton); + + /// + /// Get Force in Newtons. + /// + public double Newtons => As(ForceUnit.Newton); + + /// + /// Get Force in OunceForce. + /// + public double OunceForce => As(ForceUnit.OunceForce); + + /// + /// Get Force in Poundals. + /// + public double Poundals => As(ForceUnit.Poundal); + /// - /// Get nullable Force from nullable KilogramsForce. + /// Get Force in PoundsForce. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromKilogramsForce(QuantityValue? kilogramsforce) + public double PoundsForce => As(ForceUnit.PoundForce); + + /// + /// Get Force in TonnesForce. + /// + public double TonnesForce => As(ForceUnit.TonneForce); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceUnit unit) { - return kilogramsforce.HasValue ? FromKilogramsForce(kilogramsforce.Value) : default(Force?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Force from nullable Kilonewtons. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromKilonewtons(QuantityValue? kilonewtons) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ForceUnit unit, [CanBeNull] IFormatProvider provider) { - return kilonewtons.HasValue ? FromKilonewtons(kilonewtons.Value) : default(Force?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Force from nullable KiloPonds. + /// Get Force from Decanewtons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromKiloPonds(QuantityValue? kiloponds) + /// If value is NaN or Infinity. + public static Force FromDecanewtons(QuantityValue decanewtons) { - return kiloponds.HasValue ? FromKiloPonds(kiloponds.Value) : default(Force?); + double value = (double) decanewtons; + return new Force(value, ForceUnit.Decanewton); } - /// - /// Get nullable Force from nullable Meganewtons. + /// Get Force from Dyne. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromMeganewtons(QuantityValue? meganewtons) + /// If value is NaN or Infinity. + public static Force FromDyne(QuantityValue dyne) { - return meganewtons.HasValue ? FromMeganewtons(meganewtons.Value) : default(Force?); + double value = (double) dyne; + return new Force(value, ForceUnit.Dyn); } - /// - /// Get nullable Force from nullable Micronewtons. + /// Get Force from KilogramsForce. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromMicronewtons(QuantityValue? micronewtons) + /// If value is NaN or Infinity. + public static Force FromKilogramsForce(QuantityValue kilogramsforce) { - return micronewtons.HasValue ? FromMicronewtons(micronewtons.Value) : default(Force?); + double value = (double) kilogramsforce; + return new Force(value, ForceUnit.KilogramForce); } - /// - /// Get nullable Force from nullable Millinewtons. + /// Get Force from Kilonewtons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromMillinewtons(QuantityValue? millinewtons) + /// If value is NaN or Infinity. + public static Force FromKilonewtons(QuantityValue kilonewtons) { - return millinewtons.HasValue ? FromMillinewtons(millinewtons.Value) : default(Force?); + double value = (double) kilonewtons; + return new Force(value, ForceUnit.Kilonewton); } - /// - /// Get nullable Force from nullable Newtons. + /// Get Force from KiloPonds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromNewtons(QuantityValue? newtons) + /// If value is NaN or Infinity. + public static Force FromKiloPonds(QuantityValue kiloponds) { - return newtons.HasValue ? FromNewtons(newtons.Value) : default(Force?); + double value = (double) kiloponds; + return new Force(value, ForceUnit.KiloPond); } - /// - /// Get nullable Force from nullable OunceForce. + /// Get Force from Meganewtons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromOunceForce(QuantityValue? ounceforce) + /// If value is NaN or Infinity. + public static Force FromMeganewtons(QuantityValue meganewtons) { - return ounceforce.HasValue ? FromOunceForce(ounceforce.Value) : default(Force?); + double value = (double) meganewtons; + return new Force(value, ForceUnit.Meganewton); } - /// - /// Get nullable Force from nullable Poundals. + /// Get Force from Micronewtons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromPoundals(QuantityValue? poundals) + /// If value is NaN or Infinity. + public static Force FromMicronewtons(QuantityValue micronewtons) { - return poundals.HasValue ? FromPoundals(poundals.Value) : default(Force?); + double value = (double) micronewtons; + return new Force(value, ForceUnit.Micronewton); } - /// - /// Get nullable Force from nullable PoundsForce. + /// Get Force from Millinewtons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromPoundsForce(QuantityValue? poundsforce) + /// If value is NaN or Infinity. + public static Force FromMillinewtons(QuantityValue millinewtons) { - return poundsforce.HasValue ? FromPoundsForce(poundsforce.Value) : default(Force?); + double value = (double) millinewtons; + return new Force(value, ForceUnit.Millinewton); + } + /// + /// Get Force from Newtons. + /// + /// If value is NaN or Infinity. + public static Force FromNewtons(QuantityValue newtons) + { + double value = (double) newtons; + return new Force(value, ForceUnit.Newton); + } + /// + /// Get Force from OunceForce. + /// + /// If value is NaN or Infinity. + public static Force FromOunceForce(QuantityValue ounceforce) + { + double value = (double) ounceforce; + return new Force(value, ForceUnit.OunceForce); + } + /// + /// Get Force from Poundals. + /// + /// If value is NaN or Infinity. + public static Force FromPoundals(QuantityValue poundals) + { + double value = (double) poundals; + return new Force(value, ForceUnit.Poundal); + } + /// + /// Get Force from PoundsForce. + /// + /// If value is NaN or Infinity. + public static Force FromPoundsForce(QuantityValue poundsforce) + { + double value = (double) poundsforce; + return new Force(value, ForceUnit.PoundForce); } - /// - /// Get nullable Force from nullable TonnesForce. + /// Get Force from TonnesForce. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Force? FromTonnesForce(QuantityValue? tonnesforce) + /// If value is NaN or Infinity. + public static Force FromTonnesForce(QuantityValue tonnesforce) { - return tonnesforce.HasValue ? FromTonnesForce(tonnesforce.Value) : default(Force?); + double value = (double) tonnesforce; + return new Force(value, ForceUnit.TonneForce); } /// @@ -185,28 +365,156 @@ public partial struct Force : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Force unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Force? From(QuantityValue? value, ForceUnit fromUnit) + public static Force From(QuantityValue value, ForceUnit fromUnit) { - return value.HasValue ? new Force((double)value.Value, fromUnit) : default(Force?); + return new Force((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Force Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Force result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Force result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ForceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ForceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ForceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static Force operator -(Force right) @@ -246,6 +554,8 @@ public static string GetAbbreviation(ForceUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Force left, Force right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -266,180 +576,240 @@ public static string GetAbbreviation(ForceUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Force, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Force left, Force right) + public static bool operator ==(Force left, Force right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Force, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Force left, Force right) + public static bool operator !=(Force left, Force right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Force other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Force Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Force other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtons(x.Newtons + y.Newtons)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Force result) + /// A hash code for the current Force. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Force); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Force to another Force with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Force with the specified unit. + public Force ToUnit(ForceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Force(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case ForceUnit.Decanewton: return (_value) * 1e1d; + case ForceUnit.Dyn: return _value/1e5; + case ForceUnit.KilogramForce: return _value*9.80665002864; + case ForceUnit.Kilonewton: return (_value) * 1e3d; + case ForceUnit.KiloPond: return _value*9.80665002864; + case ForceUnit.Meganewton: return (_value) * 1e6d; + case ForceUnit.Micronewton: return (_value) * 1e-6d; + case ForceUnit.Millinewton: return (_value) * 1e-3d; + case ForceUnit.Newton: return _value; + case ForceUnit.OunceForce: return _value*2.780138509537812e-1; + case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return _value*9.80665002864e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(ForceUnit unit) + { + if(Unit == unit) + return _value; - if (unit == ForceUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; + case ForceUnit.Dyn: return baseUnitValue*1e5; + case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; + case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; + case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; + case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; + case ForceUnit.Micronewton: return (baseUnitValue) / 1e-6d; + case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; + case ForceUnit.Newton: return baseUnitValue; + case ForceUnit.OunceForce: return baseUnitValue/2.780138509537812e-1; + case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return baseUnitValue/9.80665002864e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ForceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs index cdd71f0625..0d6065acc8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,114 +49,286 @@ namespace UnitsNet /// /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ForceChangeRate : IComparable, IComparable + public partial struct ForceChangeRate : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ForceChangeRate from nullable CentinewtonsPerSecond. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromCentinewtonsPerSecond(QuantityValue? centinewtonspersecond) + private readonly ForceChangeRateUnit? _unit; + + static ForceChangeRate() { - return centinewtonspersecond.HasValue ? FromCentinewtonsPerSecond(centinewtonspersecond.Value) : default(ForceChangeRate?); + BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); } /// - /// Get nullable ForceChangeRate from nullable DecanewtonsPerMinute. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromDecanewtonsPerMinute(QuantityValue? decanewtonsperminute) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ForceChangeRate(double numericValue, ForceChangeRateUnit unit) { - return decanewtonsperminute.HasValue ? FromDecanewtonsPerMinute(decanewtonsperminute.Value) : default(ForceChangeRate?); + if(unit == ForceChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. + /// + public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; + + /// + /// Represents the largest possible value of ForceChangeRate + /// + public static ForceChangeRate MaxValue => new ForceChangeRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ForceChangeRate + /// + public static ForceChangeRate MinValue => new ForceChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ForceChangeRate; + + /// + /// All units of measurement for the ForceChangeRate quantity. + /// + public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. + /// + public static ForceChangeRate Zero => new ForceChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForceChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ForceChangeRate in CentinewtonsPerSecond. + /// + public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); + + /// + /// Get ForceChangeRate in DecanewtonsPerMinute. + /// + public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); + + /// + /// Get ForceChangeRate in DecanewtonsPerSecond. + /// + public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); + + /// + /// Get ForceChangeRate in DecinewtonsPerSecond. + /// + public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); + + /// + /// Get ForceChangeRate in KilonewtonsPerMinute. + /// + public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); + + /// + /// Get ForceChangeRate in KilonewtonsPerSecond. + /// + public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); + + /// + /// Get ForceChangeRate in MicronewtonsPerSecond. + /// + public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); + + /// + /// Get ForceChangeRate in MillinewtonsPerSecond. + /// + public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); + + /// + /// Get ForceChangeRate in NanonewtonsPerSecond. + /// + public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); + + /// + /// Get ForceChangeRate in NewtonsPerMinute. + /// + public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); + + /// + /// Get ForceChangeRate in NewtonsPerSecond. + /// + public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); + + #endregion + + #region Static Methods + /// - /// Get nullable ForceChangeRate from nullable DecanewtonsPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromDecanewtonsPerSecond(QuantityValue? decanewtonspersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForceChangeRateUnit unit) { - return decanewtonspersecond.HasValue ? FromDecanewtonsPerSecond(decanewtonspersecond.Value) : default(ForceChangeRate?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ForceChangeRate from nullable DecinewtonsPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromDecinewtonsPerSecond(QuantityValue? decinewtonspersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider) { - return decinewtonspersecond.HasValue ? FromDecinewtonsPerSecond(decinewtonspersecond.Value) : default(ForceChangeRate?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable ForceChangeRate from nullable KilonewtonsPerMinute. + /// Get ForceChangeRate from CentinewtonsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromKilonewtonsPerMinute(QuantityValue? kilonewtonsperminute) + /// If value is NaN or Infinity. + public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) { - return kilonewtonsperminute.HasValue ? FromKilonewtonsPerMinute(kilonewtonsperminute.Value) : default(ForceChangeRate?); + double value = (double) centinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); } - /// - /// Get nullable ForceChangeRate from nullable KilonewtonsPerSecond. + /// Get ForceChangeRate from DecanewtonsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromKilonewtonsPerSecond(QuantityValue? kilonewtonspersecond) + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) { - return kilonewtonspersecond.HasValue ? FromKilonewtonsPerSecond(kilonewtonspersecond.Value) : default(ForceChangeRate?); + double value = (double) decanewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); } - /// - /// Get nullable ForceChangeRate from nullable MicronewtonsPerSecond. + /// Get ForceChangeRate from DecanewtonsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromMicronewtonsPerSecond(QuantityValue? micronewtonspersecond) + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) { - return micronewtonspersecond.HasValue ? FromMicronewtonsPerSecond(micronewtonspersecond.Value) : default(ForceChangeRate?); + double value = (double) decanewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); } - /// - /// Get nullable ForceChangeRate from nullable MillinewtonsPerSecond. + /// Get ForceChangeRate from DecinewtonsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromMillinewtonsPerSecond(QuantityValue? millinewtonspersecond) + /// If value is NaN or Infinity. + public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) { - return millinewtonspersecond.HasValue ? FromMillinewtonsPerSecond(millinewtonspersecond.Value) : default(ForceChangeRate?); + double value = (double) decinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); } - /// - /// Get nullable ForceChangeRate from nullable NanonewtonsPerSecond. + /// Get ForceChangeRate from KilonewtonsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromNanonewtonsPerSecond(QuantityValue? nanonewtonspersecond) + /// If value is NaN or Infinity. + public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) { - return nanonewtonspersecond.HasValue ? FromNanonewtonsPerSecond(nanonewtonspersecond.Value) : default(ForceChangeRate?); + double value = (double) kilonewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); } - /// - /// Get nullable ForceChangeRate from nullable NewtonsPerMinute. + /// Get ForceChangeRate from KilonewtonsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromNewtonsPerMinute(QuantityValue? newtonsperminute) + /// If value is NaN or Infinity. + public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) { - return newtonsperminute.HasValue ? FromNewtonsPerMinute(newtonsperminute.Value) : default(ForceChangeRate?); + double value = (double) kilonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); + } + /// + /// Get ForceChangeRate from MicronewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) + { + double value = (double) micronewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); } - /// - /// Get nullable ForceChangeRate from nullable NewtonsPerSecond. + /// Get ForceChangeRate from MillinewtonsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForceChangeRate? FromNewtonsPerSecond(QuantityValue? newtonspersecond) + /// If value is NaN or Infinity. + public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) { - return newtonspersecond.HasValue ? FromNewtonsPerSecond(newtonspersecond.Value) : default(ForceChangeRate?); + double value = (double) millinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); + } + /// + /// Get ForceChangeRate from NanonewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) + { + double value = (double) nanonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); + } + /// + /// Get ForceChangeRate from NewtonsPerMinute. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) + { + double value = (double) newtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); + } + /// + /// Get ForceChangeRate from NewtonsPerSecond. + /// + /// If value is NaN or Infinity. + public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) + { + double value = (double) newtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); } /// @@ -167,28 +337,156 @@ public partial struct ForceChangeRate : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ForceChangeRate unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForceChangeRate? From(QuantityValue? value, ForceChangeRateUnit fromUnit) + public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) { - return value.HasValue ? new ForceChangeRate((double)value.Value, fromUnit) : default(ForceChangeRate?); + return new ForceChangeRate((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ForceChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForceChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ForceChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ForceChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); } + public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ForceChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ForceChangeRate operator -(ForceChangeRate right) @@ -228,6 +526,8 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] IForm #endregion + #region Equality / IComparable + public static bool operator <=(ForceChangeRate left, ForceChangeRate right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -248,180 +548,236 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] IForm return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForceChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ForceChangeRate left, ForceChangeRate right) + public static bool operator ==(ForceChangeRate left, ForceChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForceChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ForceChangeRate left, ForceChangeRate right) + public static bool operator !=(ForceChangeRate left, ForceChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ForceChangeRate other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForceChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ForceChangeRate other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForceChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerSecond(x.NewtonsPerSecond + y.NewtonsPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForceChangeRate result) + /// A hash code for the current ForceChangeRate. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ForceChangeRate); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ForceChangeRate with the specified unit. + public ForceChangeRate ToUnit(ForceChangeRateUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ForceChangeRate(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return _value/60; + case ForceChangeRateUnit.NewtonPerSecond: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(ForceChangeRateUnit unit) + { + if(Unit == unit) + return _value; - if (unit == ForceChangeRateUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; + case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs index 66ab9ff940..1cf9184c55 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,96 +49,258 @@ namespace UnitsNet /// /// The magnitude of force per unit length. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ForcePerLength : IComparable, IComparable + public partial struct ForcePerLength : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ForcePerLength from nullable CentinewtonsPerMeter. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromCentinewtonsPerMeter(QuantityValue? centinewtonspermeter) + private readonly ForcePerLengthUnit? _unit; + + static ForcePerLength() { - return centinewtonspermeter.HasValue ? FromCentinewtonsPerMeter(centinewtonspermeter.Value) : default(ForcePerLength?); + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable ForcePerLength from nullable DecinewtonsPerMeter. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromDecinewtonsPerMeter(QuantityValue? decinewtonspermeter) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ForcePerLength(double numericValue, ForcePerLengthUnit unit) { - return decinewtonspermeter.HasValue ? FromDecinewtonsPerMeter(decinewtonspermeter.Value) : default(ForcePerLength?); + if(unit == ForcePerLengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. + /// + public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; + + /// + /// Represents the largest possible value of ForcePerLength + /// + public static ForcePerLength MaxValue => new ForcePerLength(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ForcePerLength + /// + public static ForcePerLength MinValue => new ForcePerLength(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ForcePerLength; + + /// + /// All units of measurement for the ForcePerLength quantity. + /// + public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. + /// + public static ForcePerLength Zero => new ForcePerLength(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ForcePerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ForcePerLength in CentinewtonsPerMeter. + /// + public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); + + /// + /// Get ForcePerLength in DecinewtonsPerMeter. + /// + public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); + + /// + /// Get ForcePerLength in KilogramsForcePerMeter. + /// + public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); + + /// + /// Get ForcePerLength in KilonewtonsPerMeter. + /// + public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); + + /// + /// Get ForcePerLength in MeganewtonsPerMeter. + /// + public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); + + /// + /// Get ForcePerLength in MicronewtonsPerMeter. + /// + public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); + + /// + /// Get ForcePerLength in MillinewtonsPerMeter. + /// + public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); + + /// + /// Get ForcePerLength in NanonewtonsPerMeter. + /// + public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); + + /// + /// Get ForcePerLength in NewtonsPerMeter. + /// + public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); + + #endregion + + #region Static Methods + /// - /// Get nullable ForcePerLength from nullable KilogramsForcePerMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromKilogramsForcePerMeter(QuantityValue? kilogramsforcepermeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ForcePerLengthUnit unit) { - return kilogramsforcepermeter.HasValue ? FromKilogramsForcePerMeter(kilogramsforcepermeter.Value) : default(ForcePerLength?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ForcePerLength from nullable KilonewtonsPerMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromKilonewtonsPerMeter(QuantityValue? kilonewtonspermeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider) { - return kilonewtonspermeter.HasValue ? FromKilonewtonsPerMeter(kilonewtonspermeter.Value) : default(ForcePerLength?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable ForcePerLength from nullable MeganewtonsPerMeter. + /// Get ForcePerLength from CentinewtonsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromMeganewtonsPerMeter(QuantityValue? meganewtonspermeter) + /// If value is NaN or Infinity. + public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) { - return meganewtonspermeter.HasValue ? FromMeganewtonsPerMeter(meganewtonspermeter.Value) : default(ForcePerLength?); + double value = (double) centinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); } - /// - /// Get nullable ForcePerLength from nullable MicronewtonsPerMeter. + /// Get ForcePerLength from DecinewtonsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromMicronewtonsPerMeter(QuantityValue? micronewtonspermeter) + /// If value is NaN or Infinity. + public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) { - return micronewtonspermeter.HasValue ? FromMicronewtonsPerMeter(micronewtonspermeter.Value) : default(ForcePerLength?); + double value = (double) decinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); } - /// - /// Get nullable ForcePerLength from nullable MillinewtonsPerMeter. + /// Get ForcePerLength from KilogramsForcePerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromMillinewtonsPerMeter(QuantityValue? millinewtonspermeter) + /// If value is NaN or Infinity. + public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) { - return millinewtonspermeter.HasValue ? FromMillinewtonsPerMeter(millinewtonspermeter.Value) : default(ForcePerLength?); + double value = (double) kilogramsforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); } - /// - /// Get nullable ForcePerLength from nullable NanonewtonsPerMeter. + /// Get ForcePerLength from KilonewtonsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromNanonewtonsPerMeter(QuantityValue? nanonewtonspermeter) + /// If value is NaN or Infinity. + public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) { - return nanonewtonspermeter.HasValue ? FromNanonewtonsPerMeter(nanonewtonspermeter.Value) : default(ForcePerLength?); + double value = (double) kilonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); + } + /// + /// Get ForcePerLength from MeganewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) + { + double value = (double) meganewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); } - /// - /// Get nullable ForcePerLength from nullable NewtonsPerMeter. + /// Get ForcePerLength from MicronewtonsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ForcePerLength? FromNewtonsPerMeter(QuantityValue? newtonspermeter) + /// If value is NaN or Infinity. + public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) { - return newtonspermeter.HasValue ? FromNewtonsPerMeter(newtonspermeter.Value) : default(ForcePerLength?); + double value = (double) micronewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); + } + /// + /// Get ForcePerLength from MillinewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) + { + double value = (double) millinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); + } + /// + /// Get ForcePerLength from NanonewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) + { + double value = (double) nanonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); + } + /// + /// Get ForcePerLength from NewtonsPerMeter. + /// + /// If value is NaN or Infinity. + public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) + { + double value = (double) newtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); } /// @@ -149,28 +309,156 @@ public partial struct ForcePerLength : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ForcePerLength unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ForcePerLength? From(QuantityValue? value, ForcePerLengthUnit fromUnit) + public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) { - return value.HasValue ? new ForcePerLength((double)value.Value, fromUnit) : default(ForcePerLength?); + return new ForcePerLength((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ForcePerLength Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ForcePerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForcePerLength result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ForcePerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ForcePerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ForcePerLengthUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static ForcePerLength operator -(ForcePerLength right) @@ -210,6 +498,8 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(ForcePerLength left, ForcePerLength right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -230,180 +520,232 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForcePerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ForcePerLength left, ForcePerLength right) + public static bool operator ==(ForcePerLength left, ForcePerLength right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ForcePerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ForcePerLength left, ForcePerLength right) + public static bool operator !=(ForcePerLength left, ForcePerLength right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ForcePerLength other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForcePerLength Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ForcePerLength other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ForcePerLengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerMeter(x.NewtonsPerMeter + y.NewtonsPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ForcePerLength result) + /// A hash code for the current ForcePerLength. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ForcePerLength); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForcePerLengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ForcePerLength to another ForcePerLength with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ForcePerLength with the specified unit. + public ForcePerLength ToUnit(ForcePerLengthUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ForcePerLength(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForcePerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ForcePerLengthUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ForcePerLengthUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForcePerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs index 12178bc55d..b3a24c9827 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,244 @@ namespace UnitsNet /// /// The number of occurrences of a repeating event per unit time. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Frequency : IComparable, IComparable + public partial struct Frequency : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Frequency from nullable CyclesPerHour. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromCyclesPerHour(QuantityValue? cyclesperhour) + private readonly FrequencyUnit? _unit; + + static Frequency() { - return cyclesperhour.HasValue ? FromCyclesPerHour(cyclesperhour.Value) : default(Frequency?); + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); } /// - /// Get nullable Frequency from nullable CyclesPerMinute. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromCyclesPerMinute(QuantityValue? cyclesperminute) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Frequency(double numericValue, FrequencyUnit unit) { - return cyclesperminute.HasValue ? FromCyclesPerMinute(cyclesperminute.Value) : default(Frequency?); + if(unit == FrequencyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Frequency, which is Hertz. All conversions go via this value. + /// + public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; + + /// + /// Represents the largest possible value of Frequency + /// + public static Frequency MaxValue => new Frequency(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Frequency + /// + public static Frequency MinValue => new Frequency(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Frequency; + + /// + /// All units of measurement for the Frequency quantity. + /// + public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. + /// + public static Frequency Zero => new Frequency(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable Frequency from nullable Gigahertz. + /// The of this quantity. + /// + public QuantityType Type => Frequency.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Frequency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Frequency in CyclesPerHour. + /// + public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); + + /// + /// Get Frequency in CyclesPerMinute. + /// + public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); + + /// + /// Get Frequency in Gigahertz. + /// + public double Gigahertz => As(FrequencyUnit.Gigahertz); + + /// + /// Get Frequency in Hertz. + /// + public double Hertz => As(FrequencyUnit.Hertz); + + /// + /// Get Frequency in Kilohertz. + /// + public double Kilohertz => As(FrequencyUnit.Kilohertz); + + /// + /// Get Frequency in Megahertz. + /// + public double Megahertz => As(FrequencyUnit.Megahertz); + + /// + /// Get Frequency in RadiansPerSecond. + /// + public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); + + /// + /// Get Frequency in Terahertz. + /// + public double Terahertz => As(FrequencyUnit.Terahertz); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromGigahertz(QuantityValue? gigahertz) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FrequencyUnit unit) { - return gigahertz.HasValue ? FromGigahertz(gigahertz.Value) : default(Frequency?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Frequency from nullable Hertz. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromHertz(QuantityValue? hertz) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] IFormatProvider provider) { - return hertz.HasValue ? FromHertz(hertz.Value) : default(Frequency?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Frequency from nullable Kilohertz. + /// Get Frequency from CyclesPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromKilohertz(QuantityValue? kilohertz) + /// If value is NaN or Infinity. + public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) { - return kilohertz.HasValue ? FromKilohertz(kilohertz.Value) : default(Frequency?); + double value = (double) cyclesperhour; + return new Frequency(value, FrequencyUnit.CyclePerHour); } - /// - /// Get nullable Frequency from nullable Megahertz. + /// Get Frequency from CyclesPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromMegahertz(QuantityValue? megahertz) + /// If value is NaN or Infinity. + public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) { - return megahertz.HasValue ? FromMegahertz(megahertz.Value) : default(Frequency?); + double value = (double) cyclesperminute; + return new Frequency(value, FrequencyUnit.CyclePerMinute); } - /// - /// Get nullable Frequency from nullable RadiansPerSecond. + /// Get Frequency from Gigahertz. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromRadiansPerSecond(QuantityValue? radianspersecond) + /// If value is NaN or Infinity. + public static Frequency FromGigahertz(QuantityValue gigahertz) { - return radianspersecond.HasValue ? FromRadiansPerSecond(radianspersecond.Value) : default(Frequency?); + double value = (double) gigahertz; + return new Frequency(value, FrequencyUnit.Gigahertz); + } + /// + /// Get Frequency from Hertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromHertz(QuantityValue hertz) + { + double value = (double) hertz; + return new Frequency(value, FrequencyUnit.Hertz); + } + /// + /// Get Frequency from Kilohertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromKilohertz(QuantityValue kilohertz) + { + double value = (double) kilohertz; + return new Frequency(value, FrequencyUnit.Kilohertz); + } + /// + /// Get Frequency from Megahertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromMegahertz(QuantityValue megahertz) + { + double value = (double) megahertz; + return new Frequency(value, FrequencyUnit.Megahertz); } - /// - /// Get nullable Frequency from nullable Terahertz. + /// Get Frequency from RadiansPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Frequency? FromTerahertz(QuantityValue? terahertz) + /// If value is NaN or Infinity. + public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) { - return terahertz.HasValue ? FromTerahertz(terahertz.Value) : default(Frequency?); + double value = (double) radianspersecond; + return new Frequency(value, FrequencyUnit.RadianPerSecond); + } + /// + /// Get Frequency from Terahertz. + /// + /// If value is NaN or Infinity. + public static Frequency FromTerahertz(QuantityValue terahertz) + { + double value = (double) terahertz; + return new Frequency(value, FrequencyUnit.Terahertz); } /// @@ -140,28 +295,156 @@ public partial struct Frequency : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Frequency unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Frequency? From(QuantityValue? value, FrequencyUnit fromUnit) + public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) { - return value.HasValue ? new Frequency((double)value.Value, fromUnit) : default(Frequency?); + return new Frequency((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Frequency Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Frequency result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Frequency result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static FrequencyUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static FrequencyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out FrequencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out FrequencyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Frequency operator -(Frequency right) @@ -201,6 +484,8 @@ public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] IFormatProv #endregion + #region Equality / IComparable + public static bool operator <=(Frequency left, Frequency right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +506,230 @@ public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] IFormatProv return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Frequency, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Frequency left, Frequency right) + public static bool operator ==(Frequency left, Frequency right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Frequency, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Frequency left, Frequency right) + public static bool operator !=(Frequency left, Frequency right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Frequency other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Frequency Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Frequency other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - FrequencyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHertz(x.Hertz + y.Hertz)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Frequency result) + /// A hash code for the current Frequency. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Frequency); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FrequencyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Frequency to another Frequency with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Frequency with the specified unit. + public Frequency ToUnit(FrequencyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Frequency(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FrequencyUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case FrequencyUnit.CyclePerHour: return _value/3600; + case FrequencyUnit.CyclePerMinute: return _value/60; + case FrequencyUnit.Gigahertz: return (_value) * 1e9d; + case FrequencyUnit.Hertz: return _value; + case FrequencyUnit.Kilohertz: return (_value) * 1e3d; + case FrequencyUnit.Megahertz: return (_value) * 1e6d; + case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; + case FrequencyUnit.Terahertz: return (_value) * 1e12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(FrequencyUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == FrequencyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FrequencyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; + case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; + case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; + case FrequencyUnit.Hertz: return baseUnitValue; + case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; + case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; + case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; + case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(FrequencyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs index c4928097c1..81a2941027 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,177 +49,384 @@ namespace UnitsNet /// /// Heat flux is the flow of energy per unit of area per unit of time /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct HeatFlux : IComparable, IComparable + public partial struct HeatFlux : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable HeatFlux from nullable BtusPerHourSquareFoot. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromBtusPerHourSquareFoot(QuantityValue? btusperhoursquarefoot) + private readonly HeatFluxUnit? _unit; + + static HeatFlux() { - return btusperhoursquarefoot.HasValue ? FromBtusPerHourSquareFoot(btusperhoursquarefoot.Value) : default(HeatFlux?); + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); } /// - /// Get nullable HeatFlux from nullable BtusPerMinuteSquareFoot. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromBtusPerMinuteSquareFoot(QuantityValue? btusperminutesquarefoot) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public HeatFlux(double numericValue, HeatFluxUnit unit) { - return btusperminutesquarefoot.HasValue ? FromBtusPerMinuteSquareFoot(btusperminutesquarefoot.Value) : default(HeatFlux?); + if(unit == HeatFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. + /// + public static HeatFluxUnit BaseUnit => HeatFluxUnit.WattPerSquareMeter; + + /// + /// Represents the largest possible value of HeatFlux + /// + public static HeatFlux MaxValue => new HeatFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of HeatFlux + /// + public static HeatFlux MinValue => new HeatFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.HeatFlux; + + /// + /// All units of measurement for the HeatFlux quantity. + /// + public static HeatFluxUnit[] Units { get; } = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static HeatFlux Zero => new HeatFlux(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get HeatFlux in BtusPerHourSquareFoot. + /// + public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); + + /// + /// Get HeatFlux in BtusPerMinuteSquareFoot. + /// + public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); + + /// + /// Get HeatFlux in BtusPerSecondSquareFoot. + /// + public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); + + /// + /// Get HeatFlux in BtusPerSecondSquareInch. + /// + public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); + + /// + /// Get HeatFlux in CaloriesPerSecondSquareCentimeter. + /// + public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); + + /// + /// Get HeatFlux in CentiwattsPerSquareMeter. + /// + public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); + + /// + /// Get HeatFlux in DeciwattsPerSquareMeter. + /// + public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); + + /// + /// Get HeatFlux in KilocaloriesPerHourSquareMeter. + /// + public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); + + /// + /// Get HeatFlux in KilocaloriesPerSecondSquareCentimeter. + /// + public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + + /// + /// Get HeatFlux in KilowattsPerSquareMeter. + /// + public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); + + /// + /// Get HeatFlux in MicrowattsPerSquareMeter. + /// + public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); + + /// + /// Get HeatFlux in MilliwattsPerSquareMeter. + /// + public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); + + /// + /// Get HeatFlux in NanowattsPerSquareMeter. + /// + public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); + + /// + /// Get HeatFlux in PoundsForcePerFootSecond. + /// + public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); + + /// + /// Get HeatFlux in PoundsPerSecondCubed. + /// + public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); + + /// + /// Get HeatFlux in WattsPerSquareFoot. + /// + public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); + + /// + /// Get HeatFlux in WattsPerSquareInch. + /// + public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); + /// - /// Get nullable HeatFlux from nullable BtusPerSecondSquareFoot. + /// Get HeatFlux in WattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromBtusPerSecondSquareFoot(QuantityValue? btuspersecondsquarefoot) + public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatFluxUnit unit) { - return btuspersecondsquarefoot.HasValue ? FromBtusPerSecondSquareFoot(btuspersecondsquarefoot.Value) : default(HeatFlux?); + return GetAbbreviation(unit, null); } /// - /// Get nullable HeatFlux from nullable BtusPerSecondSquareInch. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromBtusPerSecondSquareInch(QuantityValue? btuspersecondsquareinch) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider) { - return btuspersecondsquareinch.HasValue ? FromBtusPerSecondSquareInch(btuspersecondsquareinch.Value) : default(HeatFlux?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable HeatFlux from nullable CaloriesPerSecondSquareCentimeter. + /// Get HeatFlux from BtusPerHourSquareFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromCaloriesPerSecondSquareCentimeter(QuantityValue? caloriespersecondsquarecentimeter) + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) { - return caloriespersecondsquarecentimeter.HasValue ? FromCaloriesPerSecondSquareCentimeter(caloriespersecondsquarecentimeter.Value) : default(HeatFlux?); + double value = (double) btusperhoursquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); } - /// - /// Get nullable HeatFlux from nullable CentiwattsPerSquareMeter. + /// Get HeatFlux from BtusPerMinuteSquareFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromCentiwattsPerSquareMeter(QuantityValue? centiwattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) { - return centiwattspersquaremeter.HasValue ? FromCentiwattsPerSquareMeter(centiwattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) btusperminutesquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); } - /// - /// Get nullable HeatFlux from nullable DeciwattsPerSquareMeter. + /// Get HeatFlux from BtusPerSecondSquareFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromDeciwattsPerSquareMeter(QuantityValue? deciwattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) { - return deciwattspersquaremeter.HasValue ? FromDeciwattsPerSquareMeter(deciwattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) btuspersecondsquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); } - /// - /// Get nullable HeatFlux from nullable KilocaloriesPerHourSquareMeter. + /// Get HeatFlux from BtusPerSecondSquareInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromKilocaloriesPerHourSquareMeter(QuantityValue? kilocaloriesperhoursquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) { - return kilocaloriesperhoursquaremeter.HasValue ? FromKilocaloriesPerHourSquareMeter(kilocaloriesperhoursquaremeter.Value) : default(HeatFlux?); + double value = (double) btuspersecondsquareinch; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); } - /// - /// Get nullable HeatFlux from nullable KilocaloriesPerSecondSquareCentimeter. + /// Get HeatFlux from CaloriesPerSecondSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromKilocaloriesPerSecondSquareCentimeter(QuantityValue? kilocaloriespersecondsquarecentimeter) + /// If value is NaN or Infinity. + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) { - return kilocaloriespersecondsquarecentimeter.HasValue ? FromKilocaloriesPerSecondSquareCentimeter(kilocaloriespersecondsquarecentimeter.Value) : default(HeatFlux?); + double value = (double) caloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); } - /// - /// Get nullable HeatFlux from nullable KilowattsPerSquareMeter. + /// Get HeatFlux from CentiwattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromKilowattsPerSquareMeter(QuantityValue? kilowattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) { - return kilowattspersquaremeter.HasValue ? FromKilowattsPerSquareMeter(kilowattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) centiwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable MicrowattsPerSquareMeter. + /// Get HeatFlux from DeciwattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromMicrowattsPerSquareMeter(QuantityValue? microwattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) { - return microwattspersquaremeter.HasValue ? FromMicrowattsPerSquareMeter(microwattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) deciwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable MilliwattsPerSquareMeter. + /// Get HeatFlux from KilocaloriesPerHourSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromMilliwattsPerSquareMeter(QuantityValue? milliwattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) { - return milliwattspersquaremeter.HasValue ? FromMilliwattsPerSquareMeter(milliwattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) kilocaloriesperhoursquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); } - /// - /// Get nullable HeatFlux from nullable NanowattsPerSquareMeter. + /// Get HeatFlux from KilocaloriesPerSecondSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromNanowattsPerSquareMeter(QuantityValue? nanowattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) { - return nanowattspersquaremeter.HasValue ? FromNanowattsPerSquareMeter(nanowattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) kilocaloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); } - /// - /// Get nullable HeatFlux from nullable PoundsForcePerFootSecond. + /// Get HeatFlux from KilowattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromPoundsForcePerFootSecond(QuantityValue? poundsforceperfootsecond) + /// If value is NaN or Infinity. + public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) { - return poundsforceperfootsecond.HasValue ? FromPoundsForcePerFootSecond(poundsforceperfootsecond.Value) : default(HeatFlux?); + double value = (double) kilowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable PoundsPerSecondCubed. + /// Get HeatFlux from MicrowattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromPoundsPerSecondCubed(QuantityValue? poundspersecondcubed) + /// If value is NaN or Infinity. + public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) { - return poundspersecondcubed.HasValue ? FromPoundsPerSecondCubed(poundspersecondcubed.Value) : default(HeatFlux?); + double value = (double) microwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable WattsPerSquareFoot. + /// Get HeatFlux from MilliwattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromWattsPerSquareFoot(QuantityValue? wattspersquarefoot) + /// If value is NaN or Infinity. + public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) { - return wattspersquarefoot.HasValue ? FromWattsPerSquareFoot(wattspersquarefoot.Value) : default(HeatFlux?); + double value = (double) milliwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable WattsPerSquareInch. + /// Get HeatFlux from NanowattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromWattsPerSquareInch(QuantityValue? wattspersquareinch) + /// If value is NaN or Infinity. + public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) { - return wattspersquareinch.HasValue ? FromWattsPerSquareInch(wattspersquareinch.Value) : default(HeatFlux?); + double value = (double) nanowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); } - /// - /// Get nullable HeatFlux from nullable WattsPerSquareMeter. + /// Get HeatFlux from PoundsForcePerFootSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatFlux? FromWattsPerSquareMeter(QuantityValue? wattspersquaremeter) + /// If value is NaN or Infinity. + public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue poundsforceperfootsecond) { - return wattspersquaremeter.HasValue ? FromWattsPerSquareMeter(wattspersquaremeter.Value) : default(HeatFlux?); + double value = (double) poundsforceperfootsecond; + return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); + } + /// + /// Get HeatFlux from PoundsPerSecondCubed. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromPoundsPerSecondCubed(QuantityValue poundspersecondcubed) + { + double value = (double) poundspersecondcubed; + return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); + } + /// + /// Get HeatFlux from WattsPerSquareFoot. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) + { + double value = (double) wattspersquarefoot; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); + } + /// + /// Get HeatFlux from WattsPerSquareInch. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) + { + double value = (double) wattspersquareinch; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); + } + /// + /// Get HeatFlux from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); } /// @@ -230,28 +435,156 @@ public partial struct HeatFlux : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// HeatFlux unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatFlux? From(QuantityValue? value, HeatFluxUnit fromUnit) + public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) { - return value.HasValue ? new HeatFlux((double)value.Value, fromUnit) : default(HeatFlux?); + return new HeatFlux((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static HeatFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static HeatFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static HeatFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out HeatFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static HeatFlux operator -(HeatFlux right) @@ -291,6 +624,8 @@ public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(HeatFlux left, HeatFlux right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -311,180 +646,250 @@ public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(HeatFlux left, HeatFlux right) + public static bool operator ==(HeatFlux left, HeatFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(HeatFlux left, HeatFlux right) + public static bool operator !=(HeatFlux left, HeatFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(HeatFlux other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatFlux Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - HeatFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeter(x.WattsPerSquareMeter + y.WattsPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatFlux result) + /// A hash code for the current HeatFlux. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(HeatFlux); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this HeatFlux to another HeatFlux with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static HeatFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A HeatFlux with the specified unit. + public HeatFlux ToUnit(HeatFluxUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new HeatFlux(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(HeatFluxUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - if (unit == HeatFluxUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(HeatFluxUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs index 83b62dc6fc..c355fb90d4 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct HeatTransferCoefficient : IComparable, IComparable + public partial struct HeatTransferCoefficient : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly HeatTransferCoefficientUnit? _unit; + + static HeatTransferCoefficient() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public HeatTransferCoefficient(double numericValue, HeatTransferCoefficientUnit unit) + { + if(unit == HeatTransferCoefficientUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. + /// + public static HeatTransferCoefficientUnit BaseUnit => HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + + /// + /// Represents the largest possible value of HeatTransferCoefficient + /// + public static HeatTransferCoefficient MaxValue => new HeatTransferCoefficient(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of HeatTransferCoefficient + /// + public static HeatTransferCoefficient MinValue => new HeatTransferCoefficient(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.HeatTransferCoefficient; + + /// + /// All units of measurement for the HeatTransferCoefficient quantity. + /// + public static HeatTransferCoefficientUnit[] Units { get; } = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// + public static HeatTransferCoefficient Zero => new HeatTransferCoefficient(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => HeatTransferCoefficient.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable HeatTransferCoefficient from nullable WattsPerSquareMeterCelsius. + /// Get HeatTransferCoefficient in WattsPerSquareMeterCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatTransferCoefficient? FromWattsPerSquareMeterCelsius(QuantityValue? wattspersquaremetercelsius) + public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + + /// + /// Get HeatTransferCoefficient in WattsPerSquareMeterKelvin. + /// + public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(HeatTransferCoefficientUnit unit) { - return wattspersquaremetercelsius.HasValue ? FromWattsPerSquareMeterCelsius(wattspersquaremetercelsius.Value) : default(HeatTransferCoefficient?); + return GetAbbreviation(unit, null); } /// - /// Get nullable HeatTransferCoefficient from nullable WattsPerSquareMeterKelvin. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static HeatTransferCoefficient? FromWattsPerSquareMeterKelvin(QuantityValue? wattspersquaremeterkelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider) { - return wattspersquaremeterkelvin.HasValue ? FromWattsPerSquareMeterKelvin(wattspersquaremeterkelvin.Value) : default(HeatTransferCoefficient?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterCelsius. + /// + /// If value is NaN or Infinity. + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) + { + double value = (double) wattspersquaremetercelsius; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + } + /// + /// Get HeatTransferCoefficient from WattsPerSquareMeterKelvin. + /// + /// If value is NaN or Infinity. + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) + { + double value = (double) wattspersquaremeterkelvin; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); } /// @@ -86,28 +211,156 @@ public partial struct HeatTransferCoefficient : IComparable, IComparableValue to convert from. /// Unit to convert from. /// HeatTransferCoefficient unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static HeatTransferCoefficient? From(QuantityValue? value, HeatTransferCoefficientUnit fromUnit) + public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) { - return value.HasValue ? new HeatTransferCoefficient((double)value.Value, fromUnit) : default(HeatTransferCoefficient?); + return new HeatTransferCoefficient((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static HeatTransferCoefficient Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatTransferCoefficient result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static HeatTransferCoefficientUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out HeatTransferCoefficientUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static HeatTransferCoefficient operator -(HeatTransferCoefficient right) @@ -147,6 +400,8 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNul #endregion + #region Equality / IComparable + public static bool operator <=(HeatTransferCoefficient left, HeatTransferCoefficient right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -167,180 +422,218 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNul return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatTransferCoefficient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) + public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(HeatTransferCoefficient, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) + public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(HeatTransferCoefficient other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatTransferCoefficient Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - HeatTransferCoefficientUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeterKelvin(x.WattsPerSquareMeterKelvin + y.WattsPerSquareMeterKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out HeatTransferCoefficient result) + /// A hash code for the current HeatTransferCoefficient. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(HeatTransferCoefficient); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatTransferCoefficientUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static HeatTransferCoefficientUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A HeatTransferCoefficient with the specified unit. + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new HeatTransferCoefficient(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return _value; + case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(HeatTransferCoefficientUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == HeatTransferCoefficientUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized HeatTransferCoefficientUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; + case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(HeatTransferCoefficientUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs index a4afec2ab1..c5da84031f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,191 @@ namespace UnitsNet /// /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Illuminance : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Illuminance + /// + public partial struct Illuminance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly IlluminanceUnit? _unit; + + static Illuminance() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + } /// - /// Get nullable Illuminance from nullable Kilolux. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Illuminance? FromKilolux(QuantityValue? kilolux) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Illuminance(double numericValue, IlluminanceUnit unit) { - return kilolux.HasValue ? FromKilolux(kilolux.Value) : default(Illuminance?); + if(unit == IlluminanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Illuminance, which is Lux. All conversions go via this value. + /// + public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; + + /// + /// Represents the largest possible value of Illuminance + /// + public static Illuminance MaxValue => new Illuminance(double.MaxValue, BaseUnit); + /// - /// Get nullable Illuminance from nullable Lux. + /// Represents the smallest possible value of Illuminance /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Illuminance? FromLux(QuantityValue? lux) + public static Illuminance MinValue => new Illuminance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Illuminance; + + /// + /// All units of measurement for the Illuminance quantity. + /// + public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lux. + /// + public static Illuminance Zero => new Illuminance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Illuminance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Illuminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Illuminance in Kilolux. + /// + public double Kilolux => As(IlluminanceUnit.Kilolux); + + /// + /// Get Illuminance in Lux. + /// + public double Lux => As(IlluminanceUnit.Lux); + + /// + /// Get Illuminance in Megalux. + /// + public double Megalux => As(IlluminanceUnit.Megalux); + + /// + /// Get Illuminance in Millilux. + /// + public double Millilux => As(IlluminanceUnit.Millilux); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IlluminanceUnit unit) { - return lux.HasValue ? FromLux(lux.Value) : default(Illuminance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Illuminance from nullable Megalux. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Illuminance? FromMegalux(QuantityValue? megalux) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider) { - return megalux.HasValue ? FromMegalux(megalux.Value) : default(Illuminance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get Illuminance from Kilolux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromKilolux(QuantityValue kilolux) + { + double value = (double) kilolux; + return new Illuminance(value, IlluminanceUnit.Kilolux); + } + /// + /// Get Illuminance from Lux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromLux(QuantityValue lux) + { + double value = (double) lux; + return new Illuminance(value, IlluminanceUnit.Lux); + } /// - /// Get nullable Illuminance from nullable Millilux. + /// Get Illuminance from Megalux. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Illuminance? FromMillilux(QuantityValue? millilux) + /// If value is NaN or Infinity. + public static Illuminance FromMegalux(QuantityValue megalux) { - return millilux.HasValue ? FromMillilux(millilux.Value) : default(Illuminance?); + double value = (double) megalux; + return new Illuminance(value, IlluminanceUnit.Megalux); + } + /// + /// Get Illuminance from Millilux. + /// + /// If value is NaN or Infinity. + public static Illuminance FromMillilux(QuantityValue millilux) + { + double value = (double) millilux; + return new Illuminance(value, IlluminanceUnit.Millilux); } /// @@ -104,28 +242,156 @@ public partial struct Illuminance : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Illuminance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Illuminance? From(QuantityValue? value, IlluminanceUnit fromUnit) + public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) { - return value.HasValue ? new Illuminance((double)value.Value, fromUnit) : default(Illuminance?); + return new Illuminance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Illuminance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Illuminance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Illuminance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static IlluminanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static IlluminanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IlluminanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out IlluminanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Illuminance operator -(Illuminance right) @@ -165,6 +431,8 @@ public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(Illuminance left, Illuminance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +453,222 @@ public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Illuminance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Illuminance left, Illuminance right) + public static bool operator ==(Illuminance left, Illuminance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Illuminance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Illuminance left, Illuminance right) + public static bool operator !=(Illuminance left, Illuminance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Illuminance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Illuminance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Illuminance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IlluminanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromLux(x.Lux + y.Lux)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Illuminance result) + /// A hash code for the current Illuminance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Illuminance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IlluminanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Illuminance to another Illuminance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Illuminance with the specified unit. + public Illuminance ToUnit(IlluminanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Illuminance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IlluminanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == IlluminanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IlluminanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs index 47ef375171..d713e80770 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,249 +49,496 @@ namespace UnitsNet /// /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Information : IComparable, IComparable + public partial struct Information : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; - - #region Nullable From Methods + private readonly decimal _value; /// - /// Get nullable Information from nullable Bits. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromBits(QuantityValue? bits) + private readonly InformationUnit? _unit; + + static Information() { - return bits.HasValue ? FromBits(bits.Value) : default(Information?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable Information from nullable Bytes. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromBytes(QuantityValue? bytes) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Information(decimal numericValue, InformationUnit unit) { - return bytes.HasValue ? FromBytes(bytes.Value) : default(Information?); + if(unit == InformationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Information, which is Bit. All conversions go via this value. + /// + public static InformationUnit BaseUnit => InformationUnit.Bit; + + /// + /// Represents the largest possible value of Information + /// + public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Information + /// + public static Information MinValue => new Information(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Information; + + /// + /// All units of measurement for the Information quantity. + /// + public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Bit. + /// + public static Information Zero => new Information(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public decimal Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Information.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Information.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Information in Bits. + /// + public double Bits => As(InformationUnit.Bit); + + /// + /// Get Information in Bytes. + /// + public double Bytes => As(InformationUnit.Byte); + + /// + /// Get Information in Exabits. + /// + public double Exabits => As(InformationUnit.Exabit); + + /// + /// Get Information in Exabytes. + /// + public double Exabytes => As(InformationUnit.Exabyte); + + /// + /// Get Information in Exbibits. + /// + public double Exbibits => As(InformationUnit.Exbibit); + + /// + /// Get Information in Exbibytes. + /// + public double Exbibytes => As(InformationUnit.Exbibyte); + + /// + /// Get Information in Gibibits. + /// + public double Gibibits => As(InformationUnit.Gibibit); + + /// + /// Get Information in Gibibytes. + /// + public double Gibibytes => As(InformationUnit.Gibibyte); + + /// + /// Get Information in Gigabits. + /// + public double Gigabits => As(InformationUnit.Gigabit); + + /// + /// Get Information in Gigabytes. + /// + public double Gigabytes => As(InformationUnit.Gigabyte); + + /// + /// Get Information in Kibibits. + /// + public double Kibibits => As(InformationUnit.Kibibit); + + /// + /// Get Information in Kibibytes. + /// + public double Kibibytes => As(InformationUnit.Kibibyte); + + /// + /// Get Information in Kilobits. + /// + public double Kilobits => As(InformationUnit.Kilobit); + + /// + /// Get Information in Kilobytes. + /// + public double Kilobytes => As(InformationUnit.Kilobyte); + + /// + /// Get Information in Mebibits. + /// + public double Mebibits => As(InformationUnit.Mebibit); + + /// + /// Get Information in Mebibytes. + /// + public double Mebibytes => As(InformationUnit.Mebibyte); + + /// + /// Get Information in Megabits. + /// + public double Megabits => As(InformationUnit.Megabit); + + /// + /// Get Information in Megabytes. + /// + public double Megabytes => As(InformationUnit.Megabyte); + + /// + /// Get Information in Pebibits. + /// + public double Pebibits => As(InformationUnit.Pebibit); + + /// + /// Get Information in Pebibytes. + /// + public double Pebibytes => As(InformationUnit.Pebibyte); + + /// + /// Get Information in Petabits. + /// + public double Petabits => As(InformationUnit.Petabit); + + /// + /// Get Information in Petabytes. + /// + public double Petabytes => As(InformationUnit.Petabyte); + + /// + /// Get Information in Tebibits. + /// + public double Tebibits => As(InformationUnit.Tebibit); + /// - /// Get nullable Information from nullable Exabits. + /// Get Information in Tebibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromExabits(QuantityValue? exabits) + public double Tebibytes => As(InformationUnit.Tebibyte); + + /// + /// Get Information in Terabits. + /// + public double Terabits => As(InformationUnit.Terabit); + + /// + /// Get Information in Terabytes. + /// + public double Terabytes => As(InformationUnit.Terabyte); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(InformationUnit unit) { - return exabits.HasValue ? FromExabits(exabits.Value) : default(Information?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Information from nullable Exabytes. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromExabytes(QuantityValue? exabytes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatProvider provider) { - return exabytes.HasValue ? FromExabytes(exabytes.Value) : default(Information?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Information from nullable Exbibits. + /// Get Information from Bits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromExbibits(QuantityValue? exbibits) + /// If value is NaN or Infinity. + public static Information FromBits(QuantityValue bits) { - return exbibits.HasValue ? FromExbibits(exbibits.Value) : default(Information?); + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); } - /// - /// Get nullable Information from nullable Exbibytes. + /// Get Information from Bytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromExbibytes(QuantityValue? exbibytes) + /// If value is NaN or Infinity. + public static Information FromBytes(QuantityValue bytes) { - return exbibytes.HasValue ? FromExbibytes(exbibytes.Value) : default(Information?); + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); } - /// - /// Get nullable Information from nullable Gibibits. + /// Get Information from Exabits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromGibibits(QuantityValue? gibibits) + /// If value is NaN or Infinity. + public static Information FromExabits(QuantityValue exabits) { - return gibibits.HasValue ? FromGibibits(gibibits.Value) : default(Information?); + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); } - /// - /// Get nullable Information from nullable Gibibytes. + /// Get Information from Exabytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromGibibytes(QuantityValue? gibibytes) + /// If value is NaN or Infinity. + public static Information FromExabytes(QuantityValue exabytes) { - return gibibytes.HasValue ? FromGibibytes(gibibytes.Value) : default(Information?); + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); } - /// - /// Get nullable Information from nullable Gigabits. + /// Get Information from Exbibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromGigabits(QuantityValue? gigabits) + /// If value is NaN or Infinity. + public static Information FromExbibits(QuantityValue exbibits) { - return gigabits.HasValue ? FromGigabits(gigabits.Value) : default(Information?); + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); } - /// - /// Get nullable Information from nullable Gigabytes. + /// Get Information from Exbibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromGigabytes(QuantityValue? gigabytes) + /// If value is NaN or Infinity. + public static Information FromExbibytes(QuantityValue exbibytes) { - return gigabytes.HasValue ? FromGigabytes(gigabytes.Value) : default(Information?); + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); } - /// - /// Get nullable Information from nullable Kibibits. + /// Get Information from Gibibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromKibibits(QuantityValue? kibibits) + /// If value is NaN or Infinity. + public static Information FromGibibits(QuantityValue gibibits) { - return kibibits.HasValue ? FromKibibits(kibibits.Value) : default(Information?); + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); } - /// - /// Get nullable Information from nullable Kibibytes. + /// Get Information from Gibibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromKibibytes(QuantityValue? kibibytes) + /// If value is NaN or Infinity. + public static Information FromGibibytes(QuantityValue gibibytes) { - return kibibytes.HasValue ? FromKibibytes(kibibytes.Value) : default(Information?); + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); } - /// - /// Get nullable Information from nullable Kilobits. + /// Get Information from Gigabits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromKilobits(QuantityValue? kilobits) + /// If value is NaN or Infinity. + public static Information FromGigabits(QuantityValue gigabits) { - return kilobits.HasValue ? FromKilobits(kilobits.Value) : default(Information?); + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); } - /// - /// Get nullable Information from nullable Kilobytes. + /// Get Information from Gigabytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromKilobytes(QuantityValue? kilobytes) + /// If value is NaN or Infinity. + public static Information FromGigabytes(QuantityValue gigabytes) { - return kilobytes.HasValue ? FromKilobytes(kilobytes.Value) : default(Information?); + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); } - /// - /// Get nullable Information from nullable Mebibits. + /// Get Information from Kibibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromMebibits(QuantityValue? mebibits) + /// If value is NaN or Infinity. + public static Information FromKibibits(QuantityValue kibibits) { - return mebibits.HasValue ? FromMebibits(mebibits.Value) : default(Information?); + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); } - /// - /// Get nullable Information from nullable Mebibytes. + /// Get Information from Kibibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromMebibytes(QuantityValue? mebibytes) + /// If value is NaN or Infinity. + public static Information FromKibibytes(QuantityValue kibibytes) { - return mebibytes.HasValue ? FromMebibytes(mebibytes.Value) : default(Information?); + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); } - /// - /// Get nullable Information from nullable Megabits. + /// Get Information from Kilobits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromMegabits(QuantityValue? megabits) + /// If value is NaN or Infinity. + public static Information FromKilobits(QuantityValue kilobits) { - return megabits.HasValue ? FromMegabits(megabits.Value) : default(Information?); + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); } - /// - /// Get nullable Information from nullable Megabytes. + /// Get Information from Kilobytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromMegabytes(QuantityValue? megabytes) + /// If value is NaN or Infinity. + public static Information FromKilobytes(QuantityValue kilobytes) { - return megabytes.HasValue ? FromMegabytes(megabytes.Value) : default(Information?); + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); } - /// - /// Get nullable Information from nullable Pebibits. + /// Get Information from Mebibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromPebibits(QuantityValue? pebibits) + /// If value is NaN or Infinity. + public static Information FromMebibits(QuantityValue mebibits) { - return pebibits.HasValue ? FromPebibits(pebibits.Value) : default(Information?); + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); } - /// - /// Get nullable Information from nullable Pebibytes. + /// Get Information from Mebibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromPebibytes(QuantityValue? pebibytes) + /// If value is NaN or Infinity. + public static Information FromMebibytes(QuantityValue mebibytes) { - return pebibytes.HasValue ? FromPebibytes(pebibytes.Value) : default(Information?); + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); } - /// - /// Get nullable Information from nullable Petabits. + /// Get Information from Megabits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromPetabits(QuantityValue? petabits) + /// If value is NaN or Infinity. + public static Information FromMegabits(QuantityValue megabits) { - return petabits.HasValue ? FromPetabits(petabits.Value) : default(Information?); + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); } - /// - /// Get nullable Information from nullable Petabytes. + /// Get Information from Megabytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromPetabytes(QuantityValue? petabytes) + /// If value is NaN or Infinity. + public static Information FromMegabytes(QuantityValue megabytes) { - return petabytes.HasValue ? FromPetabytes(petabytes.Value) : default(Information?); + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); } - /// - /// Get nullable Information from nullable Tebibits. + /// Get Information from Pebibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromTebibits(QuantityValue? tebibits) + /// If value is NaN or Infinity. + public static Information FromPebibits(QuantityValue pebibits) { - return tebibits.HasValue ? FromTebibits(tebibits.Value) : default(Information?); + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); } - /// - /// Get nullable Information from nullable Tebibytes. + /// Get Information from Pebibytes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromTebibytes(QuantityValue? tebibytes) + /// If value is NaN or Infinity. + public static Information FromPebibytes(QuantityValue pebibytes) { - return tebibytes.HasValue ? FromTebibytes(tebibytes.Value) : default(Information?); + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); } - /// - /// Get nullable Information from nullable Terabits. + /// Get Information from Petabits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromTerabits(QuantityValue? terabits) + /// If value is NaN or Infinity. + public static Information FromPetabits(QuantityValue petabits) { - return terabits.HasValue ? FromTerabits(terabits.Value) : default(Information?); + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); + } + /// + /// Get Information from Petabytes. + /// + /// If value is NaN or Infinity. + public static Information FromPetabytes(QuantityValue petabytes) + { + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); } - /// - /// Get nullable Information from nullable Terabytes. + /// Get Information from Tebibits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Information? FromTerabytes(QuantityValue? terabytes) + /// If value is NaN or Infinity. + public static Information FromTebibits(QuantityValue tebibits) { - return terabytes.HasValue ? FromTerabytes(terabytes.Value) : default(Information?); + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); + } + /// + /// Get Information from Tebibytes. + /// + /// If value is NaN or Infinity. + public static Information FromTebibytes(QuantityValue tebibytes) + { + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); + } + /// + /// Get Information from Terabits. + /// + /// If value is NaN or Infinity. + public static Information FromTerabits(QuantityValue terabits) + { + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); + } + /// + /// Get Information from Terabytes. + /// + /// If value is NaN or Infinity. + public static Information FromTerabytes(QuantityValue terabytes) + { + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); } /// @@ -302,28 +547,156 @@ public partial struct Information : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Information unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Information? From(QuantityValue? value, InformationUnit fromUnit) + public static Information From(QuantityValue value, InformationUnit fromUnit) { - return value.HasValue ? new Information((decimal)value.Value, fromUnit) : default(Information?); + return new Information((decimal)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Information Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically 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. + /// Format to use when parsing number and unit. Defaults to if null. + public static InformationUnit ParseUnit(string str, IFormatProvider provider = null) + { + 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")); + /// + /// 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); + } + + #endregion + #region Arithmetic Operators public static Information operator -(Information right) @@ -363,6 +736,8 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(Information left, Information right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -383,178 +758,266 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - public static bool operator ==(Information left, Information right) + public static bool operator ==(Information left, Information right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - public static bool operator !=(Information left, Information right) + public static bool operator !=(Information left, Information right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Information other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// Compare equality to another Information within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Information Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Information other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - InformationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromBits(x.Bits + y.Bits)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Information result) + /// A hash code for the current Information. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Information); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(InformationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Information to another Information with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Information with the specified unit. + public Information ToUnit(InformationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Information(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static InformationUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private decimal AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == InformationUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs index e2349c1c91..8a216b2374 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Irradiance : IComparable, IComparable + public partial struct Irradiance : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradianceUnit? _unit; + + static Irradiance() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Irradiance(double numericValue, IrradianceUnit unit) + { + if(unit == IrradianceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. + /// + public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; + + /// + /// Represents the largest possible value of Irradiance + /// + public static Irradiance MaxValue => new Irradiance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Irradiance + /// + public static Irradiance MinValue => new Irradiance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Irradiance; + + /// + /// All units of measurement for the Irradiance quantity. + /// + public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// + public static Irradiance Zero => new Irradiance(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiance.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable Irradiance from nullable KilowattsPerSquareMeter. + /// Get Irradiance in KilowattsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Irradiance? FromKilowattsPerSquareMeter(QuantityValue? kilowattspersquaremeter) + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + + /// + /// Get Irradiance in WattsPerSquareMeter. + /// + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradianceUnit unit) { - return kilowattspersquaremeter.HasValue ? FromKilowattsPerSquareMeter(kilowattspersquaremeter.Value) : default(Irradiance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Irradiance from nullable WattsPerSquareMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Irradiance? FromWattsPerSquareMeter(QuantityValue? wattspersquaremeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] IFormatProvider provider) { - return wattspersquaremeter.HasValue ? FromWattsPerSquareMeter(wattspersquaremeter.Value) : default(Irradiance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiance from KilowattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); + } + /// + /// Get Irradiance from WattsPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); } /// @@ -86,28 +211,156 @@ public partial struct Irradiance : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Irradiance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiance? From(QuantityValue? value, IrradianceUnit fromUnit) + public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) { - return value.HasValue ? new Irradiance((double)value.Value, fromUnit) : default(Irradiance?); + return new Irradiance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Irradiance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static IrradianceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static IrradianceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradianceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out IrradianceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Irradiance operator -(Irradiance right) @@ -147,6 +400,8 @@ public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] IFormatPro #endregion + #region Equality / IComparable + public static bool operator <=(Irradiance left, Irradiance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -167,180 +422,218 @@ public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] IFormatPro return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Irradiance left, Irradiance right) + public static bool operator ==(Irradiance left, Irradiance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Irradiance left, Irradiance right) + public static bool operator !=(Irradiance left, Irradiance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Irradiance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Irradiance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IrradianceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerSquareMeter(x.WattsPerSquareMeter + y.WattsPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiance result) + /// A hash code for the current Irradiance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Irradiance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradianceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Irradiance to another Irradiance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Irradiance with the specified unit. + public Irradiance ToUnit(IrradianceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Irradiance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradianceUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; + case IrradianceUnit.WattPerSquareMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(IrradianceUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == IrradianceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradianceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; + case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(IrradianceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs index 9b93e36357..9661a629eb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,177 @@ namespace UnitsNet /// /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Irradiation : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Irradiation + /// + public partial struct Irradiation : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradiationUnit? _unit; + + static Irradiation() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Irradiation(double numericValue, IrradiationUnit unit) + { + if(unit == IrradiationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. + /// + public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; + + /// + /// Represents the largest possible value of Irradiation + /// + public static Irradiation MaxValue => new Irradiation(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Irradiation + /// + public static Irradiation MinValue => new Irradiation(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Irradiation; + + /// + /// All units of measurement for the Irradiation quantity. + /// + public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// + public static Irradiation Zero => new Irradiation(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Irradiation.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Irradiation.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable Irradiation from nullable JoulesPerSquareMeter. + /// Get Irradiation in JoulesPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Irradiation? FromJoulesPerSquareMeter(QuantityValue? joulespersquaremeter) + public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); + + /// + /// Get Irradiation in KilowattHoursPerSquareMeter. + /// + public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); + + /// + /// Get Irradiation in WattHoursPerSquareMeter. + /// + public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(IrradiationUnit unit) { - return joulespersquaremeter.HasValue ? FromJoulesPerSquareMeter(joulespersquaremeter.Value) : default(Irradiation?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Irradiation from nullable KilowattHoursPerSquareMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Irradiation? FromKilowattHoursPerSquareMeter(QuantityValue? kilowatthourspersquaremeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] IFormatProvider provider) { - return kilowatthourspersquaremeter.HasValue ? FromKilowattHoursPerSquareMeter(kilowatthourspersquaremeter.Value) : default(Irradiation?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get Irradiation from JoulesPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) + { + double value = (double) joulespersquaremeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); + } /// - /// Get nullable Irradiation from nullable WattHoursPerSquareMeter. + /// Get Irradiation from KilowattHoursPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Irradiation? FromWattHoursPerSquareMeter(QuantityValue? watthourspersquaremeter) + /// If value is NaN or Infinity. + public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) { - return watthourspersquaremeter.HasValue ? FromWattHoursPerSquareMeter(watthourspersquaremeter.Value) : default(Irradiation?); + double value = (double) kilowatthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); + } + /// + /// Get Irradiation from WattHoursPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) + { + double value = (double) watthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); } /// @@ -95,28 +228,156 @@ public partial struct Irradiation : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Irradiation unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Irradiation? From(QuantityValue? value, IrradiationUnit fromUnit) + public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) { - return value.HasValue ? new Irradiation((double)value.Value, fromUnit) : default(Irradiation?); + return new Irradiation((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Irradiation Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Irradiation result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiation result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static IrradiationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static IrradiationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out IrradiationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out IrradiationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Irradiation operator -(Irradiation right) @@ -156,6 +417,8 @@ public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(Irradiation left, Irradiation right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +439,220 @@ public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiation, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Irradiation left, Irradiation right) + public static bool operator ==(Irradiation left, Irradiation right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Irradiation, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Irradiation left, Irradiation right) + public static bool operator !=(Irradiation left, Irradiation right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Irradiation other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiation Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Irradiation other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - IrradiationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerSquareMeter(x.JoulesPerSquareMeter + y.JoulesPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Irradiation result) + /// A hash code for the current Irradiation. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Irradiation); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradiationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Irradiation to another Irradiation with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Irradiation with the specified unit. + public Irradiation ToUnit(IrradiationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Irradiation(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradiationUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case IrradiationUnit.JoulePerSquareMeter: return _value; + case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(IrradiationUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == IrradiationUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradiationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; + case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(IrradiationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs index 130189e842..7f291dac8a 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,247 @@ namespace UnitsNet /// /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct KinematicViscosity : IComparable, IComparable + /// + /// http://en.wikipedia.org/wiki/Viscosity + /// + public partial struct KinematicViscosity : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable KinematicViscosity from nullable Centistokes. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromCentistokes(QuantityValue? centistokes) + private readonly KinematicViscosityUnit? _unit; + + static KinematicViscosity() { - return centistokes.HasValue ? FromCentistokes(centistokes.Value) : default(KinematicViscosity?); + BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); } /// - /// Get nullable KinematicViscosity from nullable Decistokes. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromDecistokes(QuantityValue? decistokes) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public KinematicViscosity(double numericValue, KinematicViscosityUnit unit) { - return decistokes.HasValue ? FromDecistokes(decistokes.Value) : default(KinematicViscosity?); + if(unit == KinematicViscosityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. + /// + public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; + + /// + /// Represents the largest possible value of KinematicViscosity + /// + public static KinematicViscosity MaxValue => new KinematicViscosity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of KinematicViscosity + /// + public static KinematicViscosity MinValue => new KinematicViscosity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.KinematicViscosity; + + /// + /// All units of measurement for the KinematicViscosity quantity. + /// + public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// + public static KinematicViscosity Zero => new KinematicViscosity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable KinematicViscosity from nullable Kilostokes. + /// The of this quantity. + /// + public QuantityType Type => KinematicViscosity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get KinematicViscosity in Centistokes. + /// + public double Centistokes => As(KinematicViscosityUnit.Centistokes); + + /// + /// Get KinematicViscosity in Decistokes. + /// + public double Decistokes => As(KinematicViscosityUnit.Decistokes); + + /// + /// Get KinematicViscosity in Kilostokes. + /// + public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); + + /// + /// Get KinematicViscosity in Microstokes. + /// + public double Microstokes => As(KinematicViscosityUnit.Microstokes); + + /// + /// Get KinematicViscosity in Millistokes. + /// + public double Millistokes => As(KinematicViscosityUnit.Millistokes); + + /// + /// Get KinematicViscosity in Nanostokes. + /// + public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); + + /// + /// Get KinematicViscosity in SquareMetersPerSecond. + /// + public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); + + /// + /// Get KinematicViscosity in Stokes. + /// + public double Stokes => As(KinematicViscosityUnit.Stokes); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromKilostokes(QuantityValue? kilostokes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(KinematicViscosityUnit unit) { - return kilostokes.HasValue ? FromKilostokes(kilostokes.Value) : default(KinematicViscosity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable KinematicViscosity from nullable Microstokes. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromMicrostokes(QuantityValue? microstokes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider) { - return microstokes.HasValue ? FromMicrostokes(microstokes.Value) : default(KinematicViscosity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable KinematicViscosity from nullable Millistokes. + /// Get KinematicViscosity from Centistokes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromMillistokes(QuantityValue? millistokes) + /// If value is NaN or Infinity. + public static KinematicViscosity FromCentistokes(QuantityValue centistokes) { - return millistokes.HasValue ? FromMillistokes(millistokes.Value) : default(KinematicViscosity?); + double value = (double) centistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); } - /// - /// Get nullable KinematicViscosity from nullable Nanostokes. + /// Get KinematicViscosity from Decistokes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromNanostokes(QuantityValue? nanostokes) + /// If value is NaN or Infinity. + public static KinematicViscosity FromDecistokes(QuantityValue decistokes) { - return nanostokes.HasValue ? FromNanostokes(nanostokes.Value) : default(KinematicViscosity?); + double value = (double) decistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); } - /// - /// Get nullable KinematicViscosity from nullable SquareMetersPerSecond. + /// Get KinematicViscosity from Kilostokes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromSquareMetersPerSecond(QuantityValue? squaremeterspersecond) + /// If value is NaN or Infinity. + public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) { - return squaremeterspersecond.HasValue ? FromSquareMetersPerSecond(squaremeterspersecond.Value) : default(KinematicViscosity?); + double value = (double) kilostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); + } + /// + /// Get KinematicViscosity from Microstokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) + { + double value = (double) microstokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); + } + /// + /// Get KinematicViscosity from Millistokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromMillistokes(QuantityValue millistokes) + { + double value = (double) millistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); + } + /// + /// Get KinematicViscosity from Nanostokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) + { + double value = (double) nanostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); } - /// - /// Get nullable KinematicViscosity from nullable Stokes. + /// Get KinematicViscosity from SquareMetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static KinematicViscosity? FromStokes(QuantityValue? stokes) + /// If value is NaN or Infinity. + public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) { - return stokes.HasValue ? FromStokes(stokes.Value) : default(KinematicViscosity?); + double value = (double) squaremeterspersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); + } + /// + /// Get KinematicViscosity from Stokes. + /// + /// If value is NaN or Infinity. + public static KinematicViscosity FromStokes(QuantityValue stokes) + { + double value = (double) stokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); } /// @@ -140,28 +298,156 @@ public partial struct KinematicViscosity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// KinematicViscosity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static KinematicViscosity? From(QuantityValue? value, KinematicViscosityUnit fromUnit) + public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) { - return value.HasValue ? new KinematicViscosity((double)value.Value, fromUnit) : default(KinematicViscosity?); + return new KinematicViscosity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static KinematicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out KinematicViscosity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static KinematicViscosityUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static KinematicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out KinematicViscosityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static KinematicViscosity operator -(KinematicViscosity right) @@ -201,6 +487,8 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] IF #endregion + #region Equality / IComparable + public static bool operator <=(KinematicViscosity left, KinematicViscosity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +509,230 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] IF return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(KinematicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(KinematicViscosity left, KinematicViscosity right) + public static bool operator ==(KinematicViscosity left, KinematicViscosity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(KinematicViscosity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(KinematicViscosity left, KinematicViscosity right) + public static bool operator !=(KinematicViscosity left, KinematicViscosity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(KinematicViscosity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static KinematicViscosity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(KinematicViscosity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - KinematicViscosityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMetersPerSecond(x.SquareMetersPerSecond + y.SquareMetersPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out KinematicViscosity result) + /// A hash code for the current KinematicViscosity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(KinematicViscosity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(KinematicViscosityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A KinematicViscosity with the specified unit. + public KinematicViscosity ToUnit(KinematicViscosityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new KinematicViscosity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static KinematicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; + case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; + case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; + case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return _value; + case KinematicViscosityUnit.Stokes: return _value/1e4; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(KinematicViscosityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == KinematicViscosityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized KinematicViscosityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; + case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; + case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; + case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; + case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs index 35de054c2f..be4066d7f3 100644 --- a/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,146 @@ namespace UnitsNet /// /// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct LapseRate : IComparable, IComparable + public partial struct LapseRate : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LapseRateUnit? _unit; + + static LapseRate() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public LapseRate(double numericValue, LapseRateUnit unit) + { + if(unit == LapseRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. + /// + public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; + + /// + /// Represents the largest possible value of LapseRate + /// + public static LapseRate MaxValue => new LapseRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LapseRate + /// + public static LapseRate MinValue => new LapseRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LapseRate; + + /// + /// All units of measurement for the LapseRate quantity. + /// + public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. + /// + public static LapseRate Zero => new LapseRate(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LapseRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LapseRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LapseRate in DegreesCelciusPerKilometer. + /// + public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LapseRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable LapseRate from nullable DegreesCelciusPerKilometer. + /// Get LapseRate from DegreesCelciusPerKilometer. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LapseRate? FromDegreesCelciusPerKilometer(QuantityValue? degreescelciusperkilometer) + /// If value is NaN or Infinity. + public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) { - return degreescelciusperkilometer.HasValue ? FromDegreesCelciusPerKilometer(degreescelciusperkilometer.Value) : default(LapseRate?); + double value = (double) degreescelciusperkilometer; + return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); } /// @@ -77,28 +197,156 @@ public partial struct LapseRate : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// LapseRate unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LapseRate? From(QuantityValue? value, LapseRateUnit fromUnit) + public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) { - return value.HasValue ? new LapseRate((double)value.Value, fromUnit) : default(LapseRate?); + return new LapseRate((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static LapseRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LapseRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LapseRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static LapseRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static LapseRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LapseRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out LapseRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static LapseRate operator -(LapseRate right) @@ -138,6 +386,8 @@ public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] IFormatProv #endregion + #region Equality / IComparable + public static bool operator <=(LapseRate left, LapseRate right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +408,216 @@ public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] IFormatProv return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LapseRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(LapseRate left, LapseRate right) + public static bool operator ==(LapseRate left, LapseRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LapseRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(LapseRate left, LapseRate right) + public static bool operator !=(LapseRate left, LapseRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(LapseRate other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LapseRate Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LapseRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegreesCelciusPerKilometer(x.DegreesCelciusPerKilometer + y.DegreesCelciusPerKilometer)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LapseRate result) + /// A hash code for the current LapseRate. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(LapseRate); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LapseRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this LapseRate to another LapseRate with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A LapseRate with the specified unit. + public LapseRate ToUnit(LapseRateUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new LapseRate(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LapseRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LapseRateUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LapseRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LapseRateUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs index dde62cc1b2..e03e322247 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,213 +49,440 @@ namespace UnitsNet /// /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Length : IComparable, IComparable + public partial struct Length : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Length from nullable Centimeters. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromCentimeters(QuantityValue? centimeters) + private readonly LengthUnit? _unit; + + static Length() { - return centimeters.HasValue ? FromCentimeters(centimeters.Value) : default(Length?); + BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); } /// - /// Get nullable Length from nullable Decimeters. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromDecimeters(QuantityValue? decimeters) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Length(double numericValue, LengthUnit unit) { - return decimeters.HasValue ? FromDecimeters(decimeters.Value) : default(Length?); + if(unit == LengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Length, which is Meter. All conversions go via this value. + /// + public static LengthUnit BaseUnit => LengthUnit.Meter; + + /// + /// Represents the largest possible value of Length + /// + public static Length MaxValue => new Length(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Length + /// + public static Length MinValue => new Length(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Length; + + /// + /// All units of measurement for the Length quantity. + /// + public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Meter. + /// + public static Length Zero => new Length(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Length.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Length.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Length in Centimeters. + /// + public double Centimeters => As(LengthUnit.Centimeter); + + /// + /// Get Length in Decimeters. + /// + public double Decimeters => As(LengthUnit.Decimeter); + + /// + /// Get Length in DtpPicas. + /// + public double DtpPicas => As(LengthUnit.DtpPica); + + /// + /// Get Length in DtpPoints. + /// + public double DtpPoints => As(LengthUnit.DtpPoint); + + /// + /// Get Length in Fathoms. + /// + public double Fathoms => As(LengthUnit.Fathom); + + /// + /// Get Length in Feet. + /// + public double Feet => As(LengthUnit.Foot); + + /// + /// Get Length in Inches. + /// + public double Inches => As(LengthUnit.Inch); + + /// + /// Get Length in Kilometers. + /// + public double Kilometers => As(LengthUnit.Kilometer); + + /// + /// Get Length in Meters. + /// + public double Meters => As(LengthUnit.Meter); + + /// + /// Get Length in Microinches. + /// + public double Microinches => As(LengthUnit.Microinch); + + /// + /// Get Length in Micrometers. + /// + public double Micrometers => As(LengthUnit.Micrometer); + + /// + /// Get Length in Mils. + /// + public double Mils => As(LengthUnit.Mil); + + /// + /// Get Length in Miles. + /// + public double Miles => As(LengthUnit.Mile); + + /// + /// Get Length in Millimeters. + /// + public double Millimeters => As(LengthUnit.Millimeter); + /// - /// Get nullable Length from nullable DtpPicas. + /// Get Length in Nanometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromDtpPicas(QuantityValue? dtppicas) + public double Nanometers => As(LengthUnit.Nanometer); + + /// + /// Get Length in NauticalMiles. + /// + public double NauticalMiles => As(LengthUnit.NauticalMile); + + /// + /// Get Length in PrinterPicas. + /// + public double PrinterPicas => As(LengthUnit.PrinterPica); + + /// + /// Get Length in PrinterPoints. + /// + public double PrinterPoints => As(LengthUnit.PrinterPoint); + + /// + /// Get Length in Shackles. + /// + public double Shackles => As(LengthUnit.Shackle); + + /// + /// Get Length in Twips. + /// + public double Twips => As(LengthUnit.Twip); + + /// + /// Get Length in UsSurveyFeet. + /// + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + + /// + /// Get Length in Yards. + /// + public double Yards => As(LengthUnit.Yard); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LengthUnit unit) { - return dtppicas.HasValue ? FromDtpPicas(dtppicas.Value) : default(Length?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Length from nullable DtpPoints. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromDtpPoints(QuantityValue? dtppoints) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvider provider) { - return dtppoints.HasValue ? FromDtpPoints(dtppoints.Value) : default(Length?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Length from nullable Fathoms. + /// Get Length from Centimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromFathoms(QuantityValue? fathoms) + /// If value is NaN or Infinity. + public static Length FromCentimeters(QuantityValue centimeters) { - return fathoms.HasValue ? FromFathoms(fathoms.Value) : default(Length?); + double value = (double) centimeters; + return new Length(value, LengthUnit.Centimeter); } - /// - /// Get nullable Length from nullable Feet. + /// Get Length from Decimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromFeet(QuantityValue? feet) + /// If value is NaN or Infinity. + public static Length FromDecimeters(QuantityValue decimeters) { - return feet.HasValue ? FromFeet(feet.Value) : default(Length?); + double value = (double) decimeters; + return new Length(value, LengthUnit.Decimeter); } - /// - /// Get nullable Length from nullable Inches. + /// Get Length from DtpPicas. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromInches(QuantityValue? inches) + /// If value is NaN or Infinity. + public static Length FromDtpPicas(QuantityValue dtppicas) { - return inches.HasValue ? FromInches(inches.Value) : default(Length?); + double value = (double) dtppicas; + return new Length(value, LengthUnit.DtpPica); } - /// - /// Get nullable Length from nullable Kilometers. + /// Get Length from DtpPoints. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromKilometers(QuantityValue? kilometers) + /// If value is NaN or Infinity. + public static Length FromDtpPoints(QuantityValue dtppoints) { - return kilometers.HasValue ? FromKilometers(kilometers.Value) : default(Length?); + double value = (double) dtppoints; + return new Length(value, LengthUnit.DtpPoint); } - /// - /// Get nullable Length from nullable Meters. + /// Get Length from Fathoms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMeters(QuantityValue? meters) + /// If value is NaN or Infinity. + public static Length FromFathoms(QuantityValue fathoms) { - return meters.HasValue ? FromMeters(meters.Value) : default(Length?); + double value = (double) fathoms; + return new Length(value, LengthUnit.Fathom); } - /// - /// Get nullable Length from nullable Microinches. + /// Get Length from Feet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMicroinches(QuantityValue? microinches) + /// If value is NaN or Infinity. + public static Length FromFeet(QuantityValue feet) { - return microinches.HasValue ? FromMicroinches(microinches.Value) : default(Length?); + double value = (double) feet; + return new Length(value, LengthUnit.Foot); } - /// - /// Get nullable Length from nullable Micrometers. + /// Get Length from Inches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMicrometers(QuantityValue? micrometers) + /// If value is NaN or Infinity. + public static Length FromInches(QuantityValue inches) { - return micrometers.HasValue ? FromMicrometers(micrometers.Value) : default(Length?); + double value = (double) inches; + return new Length(value, LengthUnit.Inch); } - /// - /// Get nullable Length from nullable Mils. + /// Get Length from Kilometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMils(QuantityValue? mils) + /// If value is NaN or Infinity. + public static Length FromKilometers(QuantityValue kilometers) { - return mils.HasValue ? FromMils(mils.Value) : default(Length?); + double value = (double) kilometers; + return new Length(value, LengthUnit.Kilometer); } - /// - /// Get nullable Length from nullable Miles. + /// Get Length from Meters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMiles(QuantityValue? miles) + /// If value is NaN or Infinity. + public static Length FromMeters(QuantityValue meters) { - return miles.HasValue ? FromMiles(miles.Value) : default(Length?); + double value = (double) meters; + return new Length(value, LengthUnit.Meter); } - /// - /// Get nullable Length from nullable Millimeters. + /// Get Length from Microinches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromMillimeters(QuantityValue? millimeters) + /// If value is NaN or Infinity. + public static Length FromMicroinches(QuantityValue microinches) { - return millimeters.HasValue ? FromMillimeters(millimeters.Value) : default(Length?); + double value = (double) microinches; + return new Length(value, LengthUnit.Microinch); } - /// - /// Get nullable Length from nullable Nanometers. + /// Get Length from Micrometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromNanometers(QuantityValue? nanometers) + /// If value is NaN or Infinity. + public static Length FromMicrometers(QuantityValue micrometers) { - return nanometers.HasValue ? FromNanometers(nanometers.Value) : default(Length?); + double value = (double) micrometers; + return new Length(value, LengthUnit.Micrometer); } - /// - /// Get nullable Length from nullable NauticalMiles. + /// Get Length from Mils. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromNauticalMiles(QuantityValue? nauticalmiles) + /// If value is NaN or Infinity. + public static Length FromMils(QuantityValue mils) { - return nauticalmiles.HasValue ? FromNauticalMiles(nauticalmiles.Value) : default(Length?); + double value = (double) mils; + return new Length(value, LengthUnit.Mil); } - /// - /// Get nullable Length from nullable PrinterPicas. + /// Get Length from Miles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromPrinterPicas(QuantityValue? printerpicas) + /// If value is NaN or Infinity. + public static Length FromMiles(QuantityValue miles) { - return printerpicas.HasValue ? FromPrinterPicas(printerpicas.Value) : default(Length?); + double value = (double) miles; + return new Length(value, LengthUnit.Mile); } - /// - /// Get nullable Length from nullable PrinterPoints. + /// Get Length from Millimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromPrinterPoints(QuantityValue? printerpoints) + /// If value is NaN or Infinity. + public static Length FromMillimeters(QuantityValue millimeters) { - return printerpoints.HasValue ? FromPrinterPoints(printerpoints.Value) : default(Length?); + double value = (double) millimeters; + return new Length(value, LengthUnit.Millimeter); } - /// - /// Get nullable Length from nullable Shackles. + /// Get Length from Nanometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromShackles(QuantityValue? shackles) + /// If value is NaN or Infinity. + public static Length FromNanometers(QuantityValue nanometers) { - return shackles.HasValue ? FromShackles(shackles.Value) : default(Length?); + double value = (double) nanometers; + return new Length(value, LengthUnit.Nanometer); } - /// - /// Get nullable Length from nullable Twips. + /// Get Length from NauticalMiles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromTwips(QuantityValue? twips) + /// If value is NaN or Infinity. + public static Length FromNauticalMiles(QuantityValue nauticalmiles) { - return twips.HasValue ? FromTwips(twips.Value) : default(Length?); + double value = (double) nauticalmiles; + return new Length(value, LengthUnit.NauticalMile); } - /// - /// Get nullable Length from nullable UsSurveyFeet. + /// Get Length from PrinterPicas. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromUsSurveyFeet(QuantityValue? ussurveyfeet) + /// If value is NaN or Infinity. + public static Length FromPrinterPicas(QuantityValue printerpicas) { - return ussurveyfeet.HasValue ? FromUsSurveyFeet(ussurveyfeet.Value) : default(Length?); + double value = (double) printerpicas; + return new Length(value, LengthUnit.PrinterPica); + } + /// + /// Get Length from PrinterPoints. + /// + /// If value is NaN or Infinity. + public static Length FromPrinterPoints(QuantityValue printerpoints) + { + double value = (double) printerpoints; + return new Length(value, LengthUnit.PrinterPoint); + } + /// + /// Get Length from Shackles. + /// + /// If value is NaN or Infinity. + public static Length FromShackles(QuantityValue shackles) + { + double value = (double) shackles; + return new Length(value, LengthUnit.Shackle); + } + /// + /// Get Length from Twips. + /// + /// If value is NaN or Infinity. + public static Length FromTwips(QuantityValue twips) + { + double value = (double) twips; + return new Length(value, LengthUnit.Twip); + } + /// + /// Get Length from UsSurveyFeet. + /// + /// If value is NaN or Infinity. + public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) + { + double value = (double) ussurveyfeet; + return new Length(value, LengthUnit.UsSurveyFoot); } - /// - /// Get nullable Length from nullable Yards. + /// Get Length from Yards. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Length? FromYards(QuantityValue? yards) + /// If value is NaN or Infinity. + public static Length FromYards(QuantityValue yards) { - return yards.HasValue ? FromYards(yards.Value) : default(Length?); + double value = (double) yards; + return new Length(value, LengthUnit.Yard); } /// @@ -266,28 +491,156 @@ public partial struct Length : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Length unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Length? From(QuantityValue? value, LengthUnit fromUnit) + public static Length From(QuantityValue value, LengthUnit fromUnit) { - return value.HasValue ? new Length((double)value.Value, fromUnit) : default(Length?); + return new Length((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Length Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out 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")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically 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. + /// Format to use when parsing number and unit. Defaults to if null. + public static LengthUnit ParseUnit(string str, IFormatProvider provider = null) + { + 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")); + /// + /// 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); + } + + #endregion + #region Arithmetic Operators public static Length operator -(Length right) @@ -327,6 +680,8 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvide #endregion + #region Equality / IComparable + public static bool operator <=(Length left, Length right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -347,180 +702,258 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] IFormatProvide return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Length, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Length left, Length right) + public static bool operator ==(Length left, Length right) + { + return left.Equals(right); + } + + public static bool operator !=(Length left, Length right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Length, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Length left, Length right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Length other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Length Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Length other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMeters(x.Meters + y.Meters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Length result) + /// A hash code for the current Length. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Length); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Length to another Length with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Length with the specified unit. + public Length ToUnit(LengthUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Length(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case LengthUnit.Centimeter: return (_value) * 1e-2d; + case LengthUnit.Decimeter: return (_value) * 1e-1d; + case LengthUnit.DtpPica: return _value/236.220472441; + case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; + case LengthUnit.Fathom: return _value*1.8288; + case LengthUnit.Foot: return _value*0.3048; + case LengthUnit.Inch: return _value*2.54e-2; + case LengthUnit.Kilometer: return (_value) * 1e3d; + case LengthUnit.Meter: return _value; + case LengthUnit.Microinch: return _value*2.54e-8; + case LengthUnit.Micrometer: return (_value) * 1e-6d; + case LengthUnit.Mil: return _value*2.54e-5; + case LengthUnit.Mile: return _value*1609.34; + case LengthUnit.Millimeter: return (_value) * 1e-3d; + case LengthUnit.Nanometer: return (_value) * 1e-9d; + case LengthUnit.NauticalMile: return _value*1852; + case LengthUnit.PrinterPica: return _value/237.106301584; + case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; + case LengthUnit.Shackle: return _value*27.432; + case LengthUnit.Twip: return _value/56692.913385826; + case LengthUnit.UsSurveyFoot: return _value*1200/3937; + case LengthUnit.Yard: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LengthUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LengthUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; + case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; + case LengthUnit.DtpPica: return baseUnitValue*236.220472441; + case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; + case LengthUnit.Fathom: return baseUnitValue/1.8288; + case LengthUnit.Foot: return baseUnitValue/0.3048; + case LengthUnit.Inch: return baseUnitValue/2.54e-2; + case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; + case LengthUnit.Meter: return baseUnitValue; + case LengthUnit.Microinch: return baseUnitValue/2.54e-8; + case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; + case LengthUnit.Mil: return baseUnitValue/2.54e-5; + case LengthUnit.Mile: return baseUnitValue/1609.34; + case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; + case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; + case LengthUnit.NauticalMile: return baseUnitValue/1852; + case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; + case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; + case LengthUnit.Shackle: return baseUnitValue/27.432; + case LengthUnit.Twip: return baseUnitValue*56692.913385826; + case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; + case LengthUnit.Yard: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs index db1899af98..e35db5d5c1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Level : IComparable, IComparable + public partial struct Level : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LevelUnit? _unit; + + static Level() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Level(double numericValue, LevelUnit unit) + { + if(unit == LevelUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Level, which is Decibel. All conversions go via this value. + /// + public static LevelUnit BaseUnit => LevelUnit.Decibel; + + /// + /// Represents the largest possible value of Level + /// + public static Level MaxValue => new Level(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Level + /// + public static Level MinValue => new Level(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Level; + + /// + /// All units of measurement for the Level quantity. + /// + public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. + /// + public static Level Zero => new Level(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Level.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Level.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable Level from nullable Decibels. + /// Get Level in Decibels. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Level? FromDecibels(QuantityValue? decibels) + public double Decibels => As(LevelUnit.Decibel); + + /// + /// Get Level in Nepers. + /// + public double Nepers => As(LevelUnit.Neper); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LevelUnit unit) { - return decibels.HasValue ? FromDecibels(decibels.Value) : default(Level?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Level from nullable Nepers. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Level? FromNepers(QuantityValue? nepers) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider provider) { - return nepers.HasValue ? FromNepers(nepers.Value) : default(Level?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get Level from Decibels. + /// + /// If value is NaN or Infinity. + public static Level FromDecibels(QuantityValue decibels) + { + double value = (double) decibels; + return new Level(value, LevelUnit.Decibel); + } + /// + /// Get Level from Nepers. + /// + /// If value is NaN or Infinity. + public static Level FromNepers(QuantityValue nepers) + { + double value = (double) nepers; + return new Level(value, LevelUnit.Neper); } /// @@ -86,28 +211,156 @@ public partial struct Level : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Level unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Level? From(QuantityValue? value, LevelUnit fromUnit) + public static Level From(QuantityValue value, LevelUnit fromUnit) { - return value.HasValue ? new Level((double)value.Value, fromUnit) : default(Level?); + return new Level((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Level Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically 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. + /// Format to use when parsing number and unit. Defaults to if null. + public static LevelUnit ParseUnit(string str, IFormatProvider provider = null) + { + 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")); + /// + /// 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); + } + + #endregion + #region Logarithmic Arithmetic Operators public static Level operator -(Level right) @@ -155,6 +408,8 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Level left, Level right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -175,180 +430,218 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Level, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Level left, Level right) + public static bool operator ==(Level left, Level right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Level, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Level left, Level right) + public static bool operator !=(Level left, Level right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Level other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Level Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Level other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LevelUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibels(x.Decibels + y.Decibels)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Level result) + /// A hash code for the current Level. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Level); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LevelUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Level to another Level with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Level with the specified unit. + public Level ToUnit(LevelUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Level(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LevelUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LevelUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LevelUnit.Decibel: return baseUnitValue; + case LevelUnit.Neper: return 0.115129254*baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs index 8f5684e2be..cbf5870f3b 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,177 @@ namespace UnitsNet /// /// The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct LinearDensity : IComparable, IComparable + /// + /// http://en.wikipedia.org/wiki/Linear_density + /// + public partial struct LinearDensity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LinearDensityUnit? _unit; + + static LinearDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public LinearDensity(double numericValue, LinearDensityUnit unit) + { + if(unit == LinearDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. + /// + public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; + + /// + /// Represents the largest possible value of LinearDensity + /// + public static LinearDensity MaxValue => new LinearDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LinearDensity + /// + public static LinearDensity MinValue => new LinearDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LinearDensity; + + /// + /// All units of measurement for the LinearDensity quantity. + /// + public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. + /// + public static LinearDensity Zero => new LinearDensity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LinearDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable LinearDensity from nullable GramsPerMeter. + /// Get LinearDensity in GramsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LinearDensity? FromGramsPerMeter(QuantityValue? gramspermeter) + public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); + + /// + /// Get LinearDensity in KilogramsPerMeter. + /// + public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); + + /// + /// Get LinearDensity in PoundsPerFoot. + /// + public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LinearDensityUnit unit) { - return gramspermeter.HasValue ? FromGramsPerMeter(gramspermeter.Value) : default(LinearDensity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable LinearDensity from nullable KilogramsPerMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LinearDensity? FromKilogramsPerMeter(QuantityValue? kilogramspermeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider) { - return kilogramspermeter.HasValue ? FromKilogramsPerMeter(kilogramspermeter.Value) : default(LinearDensity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get LinearDensity from GramsPerMeter. + /// + /// If value is NaN or Infinity. + public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) + { + double value = (double) gramspermeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); + } /// - /// Get nullable LinearDensity from nullable PoundsPerFoot. + /// Get LinearDensity from KilogramsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LinearDensity? FromPoundsPerFoot(QuantityValue? poundsperfoot) + /// If value is NaN or Infinity. + public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) { - return poundsperfoot.HasValue ? FromPoundsPerFoot(poundsperfoot.Value) : default(LinearDensity?); + double value = (double) kilogramspermeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); + } + /// + /// Get LinearDensity from PoundsPerFoot. + /// + /// If value is NaN or Infinity. + public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) + { + double value = (double) poundsperfoot; + return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); } /// @@ -95,28 +228,156 @@ public partial struct LinearDensity : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// LinearDensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LinearDensity? From(QuantityValue? value, LinearDensityUnit fromUnit) + public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) { - return value.HasValue ? new LinearDensity((double)value.Value, fromUnit) : default(LinearDensity?); + return new LinearDensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static LinearDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LinearDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LinearDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static LinearDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static LinearDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LinearDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out LinearDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static LinearDensity operator -(LinearDensity right) @@ -156,6 +417,8 @@ public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(LinearDensity left, LinearDensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +439,220 @@ public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LinearDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(LinearDensity left, LinearDensity right) + public static bool operator ==(LinearDensity left, LinearDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LinearDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(LinearDensity left, LinearDensity right) + public static bool operator !=(LinearDensity left, LinearDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(LinearDensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LinearDensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(LinearDensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LinearDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerMeter(x.KilogramsPerMeter + y.KilogramsPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LinearDensity result) + /// A hash code for the current LinearDensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(LinearDensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LinearDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this LinearDensity to another LinearDensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A LinearDensity with the specified unit. + public LinearDensity ToUnit(LinearDensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new LinearDensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LinearDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case LinearDensityUnit.GramPerMeter: return _value*1e-3; + case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; + case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(LinearDensityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LinearDensityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LinearDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; + case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; + case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs index a0bbf1d531..a7ee796bb5 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct LuminousFlux : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Luminous_flux + /// + public partial struct LuminousFlux : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousFluxUnit? _unit; + + static LuminousFlux() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public LuminousFlux(double numericValue, LuminousFluxUnit unit) + { + if(unit == LuminousFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. + /// + public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; + + /// + /// Represents the largest possible value of LuminousFlux + /// + public static LuminousFlux MaxValue => new LuminousFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LuminousFlux + /// + public static LuminousFlux MinValue => new LuminousFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LuminousFlux; + + /// + /// All units of measurement for the LuminousFlux quantity. + /// + public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. + /// + public static LuminousFlux Zero => new LuminousFlux(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousFlux in Lumens. + /// + public double Lumens => As(LuminousFluxUnit.Lumen); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable LuminousFlux from nullable Lumens. + /// Get LuminousFlux from Lumens. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LuminousFlux? FromLumens(QuantityValue? lumens) + /// If value is NaN or Infinity. + public static LuminousFlux FromLumens(QuantityValue lumens) { - return lumens.HasValue ? FromLumens(lumens.Value) : default(LuminousFlux?); + double value = (double) lumens; + return new LuminousFlux(value, LuminousFluxUnit.Lumen); } /// @@ -77,28 +200,156 @@ public partial struct LuminousFlux : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// LuminousFlux unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LuminousFlux? From(QuantityValue? value, LuminousFluxUnit fromUnit) + public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) { - return value.HasValue ? new LuminousFlux((double)value.Value, fromUnit) : default(LuminousFlux?); + return new LuminousFlux((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static LuminousFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static LuminousFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static LuminousFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out LuminousFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static LuminousFlux operator -(LuminousFlux right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(LuminousFlux left, LuminousFlux right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(LuminousFlux left, LuminousFlux right) + public static bool operator ==(LuminousFlux left, LuminousFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(LuminousFlux left, LuminousFlux right) + public static bool operator !=(LuminousFlux left, LuminousFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(LuminousFlux other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousFlux Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LuminousFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromLumens(x.Lumens + y.Lumens)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousFlux result) + /// A hash code for the current LuminousFlux. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(LuminousFlux); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this LuminousFlux to another LuminousFlux with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A LuminousFlux with the specified unit. + public LuminousFlux ToUnit(LuminousFluxUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new LuminousFlux(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LuminousFluxUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LuminousFluxUnit.Lumen: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs index d3c84a4b2b..ebfd3b327e 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct LuminousIntensity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Luminous_intensity + /// + public partial struct LuminousIntensity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousIntensityUnit? _unit; + + static LuminousIntensity() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public LuminousIntensity(double numericValue, LuminousIntensityUnit unit) + { + if(unit == LuminousIntensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. + /// + public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; + + /// + /// Represents the largest possible value of LuminousIntensity + /// + public static LuminousIntensity MaxValue => new LuminousIntensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of LuminousIntensity + /// + public static LuminousIntensity MinValue => new LuminousIntensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.LuminousIntensity; + + /// + /// All units of measurement for the LuminousIntensity quantity. + /// + public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Candela. + /// + public static LuminousIntensity Zero => new LuminousIntensity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => LuminousIntensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get LuminousIntensity in Candela. + /// + public double Candela => As(LuminousIntensityUnit.Candela); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(LuminousIntensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable LuminousIntensity from nullable Candela. + /// Get LuminousIntensity from Candela. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static LuminousIntensity? FromCandela(QuantityValue? candela) + /// If value is NaN or Infinity. + public static LuminousIntensity FromCandela(QuantityValue candela) { - return candela.HasValue ? FromCandela(candela.Value) : default(LuminousIntensity?); + double value = (double) candela; + return new LuminousIntensity(value, LuminousIntensityUnit.Candela); } /// @@ -77,28 +200,156 @@ public partial struct LuminousIntensity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// LuminousIntensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static LuminousIntensity? From(QuantityValue? value, LuminousIntensityUnit fromUnit) + public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) { - return value.HasValue ? new LuminousIntensity((double)value.Value, fromUnit) : default(LuminousIntensity?); + return new LuminousIntensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static LuminousIntensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousIntensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static LuminousIntensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static LuminousIntensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out LuminousIntensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static LuminousIntensity operator -(LuminousIntensity right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] IFo #endregion + #region Equality / IComparable + public static bool operator <=(LuminousIntensity left, LuminousIntensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] IFo return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousIntensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(LuminousIntensity left, LuminousIntensity right) + public static bool operator ==(LuminousIntensity left, LuminousIntensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(LuminousIntensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(LuminousIntensity left, LuminousIntensity right) + public static bool operator !=(LuminousIntensity left, LuminousIntensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(LuminousIntensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousIntensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(LuminousIntensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - LuminousIntensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCandela(x.Candela + y.Candela)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out LuminousIntensity result) + /// A hash code for the current LuminousIntensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(LuminousIntensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousIntensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A LuminousIntensity with the specified unit. + public LuminousIntensity ToUnit(LuminousIntensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new LuminousIntensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousIntensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == LuminousIntensityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousIntensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case LuminousIntensityUnit.Candela: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs index bd0ba78b05..3e218c9500 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,191 @@ namespace UnitsNet /// /// A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MagneticField : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Magnetic_field + /// + public partial struct MagneticField : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFieldUnit? _unit; + + static MagneticField() + { + BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); + } /// - /// Get nullable MagneticField from nullable Microteslas. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MagneticField? FromMicroteslas(QuantityValue? microteslas) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MagneticField(double numericValue, MagneticFieldUnit unit) { - return microteslas.HasValue ? FromMicroteslas(microteslas.Value) : default(MagneticField?); + if(unit == MagneticFieldUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticField, which is Tesla. All conversions go via this value. + /// + public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; + + /// + /// Represents the largest possible value of MagneticField + /// + public static MagneticField MaxValue => new MagneticField(double.MaxValue, BaseUnit); + /// - /// Get nullable MagneticField from nullable Milliteslas. + /// Represents the smallest possible value of MagneticField /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MagneticField? FromMilliteslas(QuantityValue? milliteslas) + public static MagneticField MinValue => new MagneticField(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MagneticField; + + /// + /// All units of measurement for the MagneticField quantity. + /// + public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. + /// + public static MagneticField Zero => new MagneticField(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticField.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticField in Microteslas. + /// + public double Microteslas => As(MagneticFieldUnit.Microtesla); + + /// + /// Get MagneticField in Milliteslas. + /// + public double Milliteslas => As(MagneticFieldUnit.Millitesla); + + /// + /// Get MagneticField in Nanoteslas. + /// + public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); + + /// + /// Get MagneticField in Teslas. + /// + public double Teslas => As(MagneticFieldUnit.Tesla); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFieldUnit unit) { - return milliteslas.HasValue ? FromMilliteslas(milliteslas.Value) : default(MagneticField?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MagneticField from nullable Nanoteslas. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MagneticField? FromNanoteslas(QuantityValue? nanoteslas) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider) { - return nanoteslas.HasValue ? FromNanoteslas(nanoteslas.Value) : default(MagneticField?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get MagneticField from Microteslas. + /// + /// If value is NaN or Infinity. + public static MagneticField FromMicroteslas(QuantityValue microteslas) + { + double value = (double) microteslas; + return new MagneticField(value, MagneticFieldUnit.Microtesla); + } + /// + /// Get MagneticField from Milliteslas. + /// + /// If value is NaN or Infinity. + public static MagneticField FromMilliteslas(QuantityValue milliteslas) + { + double value = (double) milliteslas; + return new MagneticField(value, MagneticFieldUnit.Millitesla); + } /// - /// Get nullable MagneticField from nullable Teslas. + /// Get MagneticField from Nanoteslas. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MagneticField? FromTeslas(QuantityValue? teslas) + /// If value is NaN or Infinity. + public static MagneticField FromNanoteslas(QuantityValue nanoteslas) { - return teslas.HasValue ? FromTeslas(teslas.Value) : default(MagneticField?); + double value = (double) nanoteslas; + return new MagneticField(value, MagneticFieldUnit.Nanotesla); + } + /// + /// Get MagneticField from Teslas. + /// + /// If value is NaN or Infinity. + public static MagneticField FromTeslas(QuantityValue teslas) + { + double value = (double) teslas; + return new MagneticField(value, MagneticFieldUnit.Tesla); } /// @@ -104,28 +242,156 @@ public partial struct MagneticField : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MagneticField unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticField? From(QuantityValue? value, MagneticFieldUnit fromUnit) + public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) { - return value.HasValue ? new MagneticField((double)value.Value, fromUnit) : default(MagneticField?); + return new MagneticField((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MagneticField Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticField result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticField result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MagneticFieldUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MagneticFieldUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MagneticFieldUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MagneticField operator -(MagneticField right) @@ -165,6 +431,8 @@ public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(MagneticField left, MagneticField right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +453,222 @@ public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MagneticField left, MagneticField right) + public static bool operator ==(MagneticField left, MagneticField right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticField, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MagneticField left, MagneticField right) + public static bool operator !=(MagneticField left, MagneticField right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MagneticField other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticField Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MagneticField other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagneticFieldUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromTeslas(x.Teslas + y.Teslas)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticField result) + /// A hash code for the current MagneticField. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MagneticField); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFieldUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MagneticField to another MagneticField with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MagneticField with the specified unit. + public MagneticField ToUnit(MagneticFieldUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MagneticField(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFieldUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case MagneticFieldUnit.Microtesla: return (_value) * 1e-6d; + 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MagneticFieldUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFieldUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MagneticFieldUnit.Microtesla: return (baseUnitValue) / 1e-6d; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs index e741ba0576..6758122032 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MagneticFlux : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Magnetic_flux + /// + public partial struct MagneticFlux : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFluxUnit? _unit; + + static MagneticFlux() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MagneticFlux(double numericValue, MagneticFluxUnit unit) + { + if(unit == MagneticFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. + /// + public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; + + /// + /// Represents the largest possible value of MagneticFlux + /// + public static MagneticFlux MaxValue => new MagneticFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MagneticFlux + /// + public static MagneticFlux MinValue => new MagneticFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MagneticFlux; + + /// + /// All units of measurement for the MagneticFlux quantity. + /// + public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Weber. + /// + public static MagneticFlux Zero => new MagneticFlux(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MagneticFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MagneticFlux in Webers. + /// + public double Webers => As(MagneticFluxUnit.Weber); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagneticFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable MagneticFlux from nullable Webers. + /// Get MagneticFlux from Webers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MagneticFlux? FromWebers(QuantityValue? webers) + /// If value is NaN or Infinity. + public static MagneticFlux FromWebers(QuantityValue webers) { - return webers.HasValue ? FromWebers(webers.Value) : default(MagneticFlux?); + double value = (double) webers; + return new MagneticFlux(value, MagneticFluxUnit.Weber); } /// @@ -77,28 +200,156 @@ public partial struct MagneticFlux : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MagneticFlux unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MagneticFlux? From(QuantityValue? value, MagneticFluxUnit fromUnit) + public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) { - return value.HasValue ? new MagneticFlux((double)value.Value, fromUnit) : default(MagneticFlux?); + return new MagneticFlux((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MagneticFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MagneticFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MagneticFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MagneticFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagneticFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MagneticFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MagneticFlux operator -(MagneticFlux right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(MagneticFlux left, MagneticFlux right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MagneticFlux left, MagneticFlux right) + public static bool operator ==(MagneticFlux left, MagneticFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MagneticFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MagneticFlux left, MagneticFlux right) + public static bool operator !=(MagneticFlux left, MagneticFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MagneticFlux other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticFlux Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagneticFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWebers(x.Webers + y.Webers)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MagneticFlux result) + /// A hash code for the current MagneticFlux. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MagneticFlux); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MagneticFlux to another MagneticFlux with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MagneticFlux with the specified unit. + public MagneticFlux ToUnit(MagneticFluxUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MagneticFlux(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MagneticFluxUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MagneticFluxUnit.Weber: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs index 9c3a9aa6b6..fb03bce307 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Magnetization : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Magnetization + /// + public partial struct Magnetization : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagnetizationUnit? _unit; + + static Magnetization() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Magnetization(double numericValue, MagnetizationUnit unit) + { + if(unit == MagnetizationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. + /// + public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; + + /// + /// Represents the largest possible value of Magnetization + /// + public static Magnetization MaxValue => new Magnetization(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Magnetization + /// + public static Magnetization MinValue => new Magnetization(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Magnetization; + + /// + /// All units of measurement for the Magnetization quantity. + /// + public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. + /// + public static Magnetization Zero => new Magnetization(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Magnetization.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Magnetization.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Magnetization in AmperesPerMeter. + /// + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MagnetizationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable Magnetization from nullable AmperesPerMeter. + /// Get Magnetization from AmperesPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Magnetization? FromAmperesPerMeter(QuantityValue? amperespermeter) + /// If value is NaN or Infinity. + public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) { - return amperespermeter.HasValue ? FromAmperesPerMeter(amperespermeter.Value) : default(Magnetization?); + double value = (double) amperespermeter; + return new Magnetization(value, MagnetizationUnit.AmperePerMeter); } /// @@ -77,28 +200,156 @@ public partial struct Magnetization : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Magnetization unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Magnetization? From(QuantityValue? value, MagnetizationUnit fromUnit) + public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) { - return value.HasValue ? new Magnetization((double)value.Value, fromUnit) : default(Magnetization?); + return new Magnetization((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Magnetization Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Magnetization result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Magnetization result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MagnetizationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MagnetizationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MagnetizationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MagnetizationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Magnetization operator -(Magnetization right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(Magnetization left, Magnetization right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Magnetization, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Magnetization left, Magnetization right) + public static bool operator ==(Magnetization left, Magnetization right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Magnetization, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Magnetization left, Magnetization right) + public static bool operator !=(Magnetization left, Magnetization right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Magnetization other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Magnetization Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Magnetization other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MagnetizationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromAmperesPerMeter(x.AmperesPerMeter + y.AmperesPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Magnetization result) + /// A hash code for the current Magnetization. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Magnetization); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagnetizationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Magnetization to another Magnetization with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Magnetization with the specified unit. + public Magnetization ToUnit(MagnetizationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Magnetization(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagnetizationUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MagnetizationUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagnetizationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MagnetizationUnit.AmperePerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs index aa140e66c8..f68c7a731b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,213 +49,440 @@ namespace UnitsNet /// /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Mass : IComparable, IComparable + public partial struct Mass : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Mass from nullable Centigrams. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromCentigrams(QuantityValue? centigrams) + private readonly MassUnit? _unit; + + static Mass() { - return centigrams.HasValue ? FromCentigrams(centigrams.Value) : default(Mass?); + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); } /// - /// Get nullable Mass from nullable Decagrams. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromDecagrams(QuantityValue? decagrams) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Mass(double numericValue, MassUnit unit) { - return decagrams.HasValue ? FromDecagrams(decagrams.Value) : default(Mass?); + if(unit == MassUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Mass, which is Kilogram. All conversions go via this value. + /// + public static MassUnit BaseUnit => MassUnit.Kilogram; + + /// + /// Represents the largest possible value of Mass + /// + public static Mass MaxValue => new Mass(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Mass + /// + public static Mass MinValue => new Mass(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Mass; + + /// + /// All units of measurement for the Mass quantity. + /// + public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. + /// + public static Mass Zero => new Mass(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Mass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Mass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Mass in Centigrams. + /// + public double Centigrams => As(MassUnit.Centigram); + + /// + /// Get Mass in Decagrams. + /// + public double Decagrams => As(MassUnit.Decagram); + + /// + /// Get Mass in Decigrams. + /// + public double Decigrams => As(MassUnit.Decigram); + + /// + /// Get Mass in Grams. + /// + public double Grams => As(MassUnit.Gram); + + /// + /// Get Mass in Hectograms. + /// + public double Hectograms => As(MassUnit.Hectogram); + + /// + /// Get Mass in Kilograms. + /// + public double Kilograms => As(MassUnit.Kilogram); + + /// + /// Get Mass in Kilopounds. + /// + public double Kilopounds => As(MassUnit.Kilopound); + + /// + /// Get Mass in Kilotonnes. + /// + public double Kilotonnes => As(MassUnit.Kilotonne); + + /// + /// Get Mass in LongHundredweight. + /// + public double LongHundredweight => As(MassUnit.LongHundredweight); + + /// + /// Get Mass in LongTons. + /// + public double LongTons => As(MassUnit.LongTon); + + /// + /// Get Mass in Megapounds. + /// + public double Megapounds => As(MassUnit.Megapound); + + /// + /// Get Mass in Megatonnes. + /// + public double Megatonnes => As(MassUnit.Megatonne); + + /// + /// Get Mass in Micrograms. + /// + public double Micrograms => As(MassUnit.Microgram); + + /// + /// Get Mass in Milligrams. + /// + public double Milligrams => As(MassUnit.Milligram); + /// - /// Get nullable Mass from nullable Decigrams. + /// Get Mass in Nanograms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromDecigrams(QuantityValue? decigrams) + public double Nanograms => As(MassUnit.Nanogram); + + /// + /// Get Mass in Ounces. + /// + public double Ounces => As(MassUnit.Ounce); + + /// + /// Get Mass in Pounds. + /// + public double Pounds => As(MassUnit.Pound); + + /// + /// Get Mass in ShortHundredweight. + /// + public double ShortHundredweight => As(MassUnit.ShortHundredweight); + + /// + /// Get Mass in ShortTons. + /// + public double ShortTons => As(MassUnit.ShortTon); + + /// + /// Get Mass in Slugs. + /// + public double Slugs => As(MassUnit.Slug); + + /// + /// Get Mass in Stone. + /// + public double Stone => As(MassUnit.Stone); + + /// + /// Get Mass in Tonnes. + /// + public double Tonnes => As(MassUnit.Tonne); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassUnit unit) { - return decigrams.HasValue ? FromDecigrams(decigrams.Value) : default(Mass?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Mass from nullable Grams. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromGrams(QuantityValue? grams) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MassUnit unit, [CanBeNull] IFormatProvider provider) { - return grams.HasValue ? FromGrams(grams.Value) : default(Mass?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Mass from nullable Hectograms. + /// Get Mass from Centigrams. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromHectograms(QuantityValue? hectograms) + /// If value is NaN or Infinity. + public static Mass FromCentigrams(QuantityValue centigrams) { - return hectograms.HasValue ? FromHectograms(hectograms.Value) : default(Mass?); + double value = (double) centigrams; + return new Mass(value, MassUnit.Centigram); } - /// - /// Get nullable Mass from nullable Kilograms. + /// Get Mass from Decagrams. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromKilograms(QuantityValue? kilograms) + /// If value is NaN or Infinity. + public static Mass FromDecagrams(QuantityValue decagrams) { - return kilograms.HasValue ? FromKilograms(kilograms.Value) : default(Mass?); + double value = (double) decagrams; + return new Mass(value, MassUnit.Decagram); } - /// - /// Get nullable Mass from nullable Kilopounds. + /// Get Mass from Decigrams. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromKilopounds(QuantityValue? kilopounds) + /// If value is NaN or Infinity. + public static Mass FromDecigrams(QuantityValue decigrams) { - return kilopounds.HasValue ? FromKilopounds(kilopounds.Value) : default(Mass?); + double value = (double) decigrams; + return new Mass(value, MassUnit.Decigram); } - /// - /// Get nullable Mass from nullable Kilotonnes. + /// Get Mass from Grams. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromKilotonnes(QuantityValue? kilotonnes) + /// If value is NaN or Infinity. + public static Mass FromGrams(QuantityValue grams) { - return kilotonnes.HasValue ? FromKilotonnes(kilotonnes.Value) : default(Mass?); + double value = (double) grams; + return new Mass(value, MassUnit.Gram); } - /// - /// Get nullable Mass from nullable LongHundredweight. + /// Get Mass from Hectograms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromLongHundredweight(QuantityValue? longhundredweight) + /// If value is NaN or Infinity. + public static Mass FromHectograms(QuantityValue hectograms) { - return longhundredweight.HasValue ? FromLongHundredweight(longhundredweight.Value) : default(Mass?); + double value = (double) hectograms; + return new Mass(value, MassUnit.Hectogram); } - /// - /// Get nullable Mass from nullable LongTons. + /// Get Mass from Kilograms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromLongTons(QuantityValue? longtons) + /// If value is NaN or Infinity. + public static Mass FromKilograms(QuantityValue kilograms) { - return longtons.HasValue ? FromLongTons(longtons.Value) : default(Mass?); + double value = (double) kilograms; + return new Mass(value, MassUnit.Kilogram); } - /// - /// Get nullable Mass from nullable Megapounds. + /// Get Mass from Kilopounds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromMegapounds(QuantityValue? megapounds) + /// If value is NaN or Infinity. + public static Mass FromKilopounds(QuantityValue kilopounds) { - return megapounds.HasValue ? FromMegapounds(megapounds.Value) : default(Mass?); + double value = (double) kilopounds; + return new Mass(value, MassUnit.Kilopound); } - /// - /// Get nullable Mass from nullable Megatonnes. + /// Get Mass from Kilotonnes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromMegatonnes(QuantityValue? megatonnes) + /// If value is NaN or Infinity. + public static Mass FromKilotonnes(QuantityValue kilotonnes) { - return megatonnes.HasValue ? FromMegatonnes(megatonnes.Value) : default(Mass?); + double value = (double) kilotonnes; + return new Mass(value, MassUnit.Kilotonne); } - /// - /// Get nullable Mass from nullable Micrograms. + /// Get Mass from LongHundredweight. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromMicrograms(QuantityValue? micrograms) + /// If value is NaN or Infinity. + public static Mass FromLongHundredweight(QuantityValue longhundredweight) { - return micrograms.HasValue ? FromMicrograms(micrograms.Value) : default(Mass?); + double value = (double) longhundredweight; + return new Mass(value, MassUnit.LongHundredweight); } - /// - /// Get nullable Mass from nullable Milligrams. + /// Get Mass from LongTons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromMilligrams(QuantityValue? milligrams) + /// If value is NaN or Infinity. + public static Mass FromLongTons(QuantityValue longtons) { - return milligrams.HasValue ? FromMilligrams(milligrams.Value) : default(Mass?); + double value = (double) longtons; + return new Mass(value, MassUnit.LongTon); } - /// - /// Get nullable Mass from nullable Nanograms. + /// Get Mass from Megapounds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromNanograms(QuantityValue? nanograms) + /// If value is NaN or Infinity. + public static Mass FromMegapounds(QuantityValue megapounds) { - return nanograms.HasValue ? FromNanograms(nanograms.Value) : default(Mass?); + double value = (double) megapounds; + return new Mass(value, MassUnit.Megapound); } - /// - /// Get nullable Mass from nullable Ounces. + /// Get Mass from Megatonnes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromOunces(QuantityValue? ounces) + /// If value is NaN or Infinity. + public static Mass FromMegatonnes(QuantityValue megatonnes) { - return ounces.HasValue ? FromOunces(ounces.Value) : default(Mass?); + double value = (double) megatonnes; + return new Mass(value, MassUnit.Megatonne); } - /// - /// Get nullable Mass from nullable Pounds. + /// Get Mass from Micrograms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromPounds(QuantityValue? pounds) + /// If value is NaN or Infinity. + public static Mass FromMicrograms(QuantityValue micrograms) { - return pounds.HasValue ? FromPounds(pounds.Value) : default(Mass?); + double value = (double) micrograms; + return new Mass(value, MassUnit.Microgram); } - /// - /// Get nullable Mass from nullable ShortHundredweight. + /// Get Mass from Milligrams. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromShortHundredweight(QuantityValue? shorthundredweight) + /// If value is NaN or Infinity. + public static Mass FromMilligrams(QuantityValue milligrams) { - return shorthundredweight.HasValue ? FromShortHundredweight(shorthundredweight.Value) : default(Mass?); + double value = (double) milligrams; + return new Mass(value, MassUnit.Milligram); } - /// - /// Get nullable Mass from nullable ShortTons. + /// Get Mass from Nanograms. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromShortTons(QuantityValue? shorttons) + /// If value is NaN or Infinity. + public static Mass FromNanograms(QuantityValue nanograms) { - return shorttons.HasValue ? FromShortTons(shorttons.Value) : default(Mass?); + double value = (double) nanograms; + return new Mass(value, MassUnit.Nanogram); } - /// - /// Get nullable Mass from nullable Slugs. + /// Get Mass from Ounces. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromSlugs(QuantityValue? slugs) + /// If value is NaN or Infinity. + public static Mass FromOunces(QuantityValue ounces) { - return slugs.HasValue ? FromSlugs(slugs.Value) : default(Mass?); + double value = (double) ounces; + return new Mass(value, MassUnit.Ounce); } - /// - /// Get nullable Mass from nullable Stone. + /// Get Mass from Pounds. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromStone(QuantityValue? stone) + /// If value is NaN or Infinity. + public static Mass FromPounds(QuantityValue pounds) { - return stone.HasValue ? FromStone(stone.Value) : default(Mass?); + double value = (double) pounds; + return new Mass(value, MassUnit.Pound); + } + /// + /// Get Mass from ShortHundredweight. + /// + /// If value is NaN or Infinity. + public static Mass FromShortHundredweight(QuantityValue shorthundredweight) + { + double value = (double) shorthundredweight; + return new Mass(value, MassUnit.ShortHundredweight); + } + /// + /// Get Mass from ShortTons. + /// + /// If value is NaN or Infinity. + public static Mass FromShortTons(QuantityValue shorttons) + { + double value = (double) shorttons; + return new Mass(value, MassUnit.ShortTon); + } + /// + /// Get Mass from Slugs. + /// + /// If value is NaN or Infinity. + public static Mass FromSlugs(QuantityValue slugs) + { + double value = (double) slugs; + return new Mass(value, MassUnit.Slug); + } + /// + /// Get Mass from Stone. + /// + /// If value is NaN or Infinity. + public static Mass FromStone(QuantityValue stone) + { + double value = (double) stone; + return new Mass(value, MassUnit.Stone); } - /// - /// Get nullable Mass from nullable Tonnes. + /// Get Mass from Tonnes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Mass? FromTonnes(QuantityValue? tonnes) + /// If value is NaN or Infinity. + public static Mass FromTonnes(QuantityValue tonnes) { - return tonnes.HasValue ? FromTonnes(tonnes.Value) : default(Mass?); + double value = (double) tonnes; + return new Mass(value, MassUnit.Tonne); } /// @@ -266,28 +491,156 @@ public partial struct Mass : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Mass unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Mass? From(QuantityValue? value, MassUnit fromUnit) + public static Mass From(QuantityValue value, MassUnit fromUnit) { - return value.HasValue ? new Mass((double)value.Value, fromUnit) : default(Mass?); + return new Mass((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Mass Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Mass result) + { + return TryParse(str, null, out result); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Mass result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MassUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MassUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MassUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Mass operator -(Mass right) @@ -327,6 +680,8 @@ public static string GetAbbreviation(MassUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Mass left, Mass right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -347,180 +702,258 @@ public static string GetAbbreviation(MassUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Mass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Mass left, Mass right) + public static bool operator ==(Mass left, Mass right) + { + return left.Equals(right); + } + + public static bool operator !=(Mass left, Mass right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Mass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Mass left, Mass right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Mass other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Mass Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilograms(x.Kilograms + y.Kilograms)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Mass result) + /// A hash code for the current Mass. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Mass); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Mass to another Mass with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Mass with the specified unit. + public Mass ToUnit(MassUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Mass(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case MassUnit.Centigram: return (_value/1e3) * 1e-2d; + case MassUnit.Decagram: return (_value/1e3) * 1e1d; + case MassUnit.Decigram: return (_value/1e3) * 1e-1d; + case MassUnit.Gram: return _value/1e3; + case MassUnit.Hectogram: return (_value/1e3) * 1e2d; + case MassUnit.Kilogram: return (_value/1e3) * 1e3d; + case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; + case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; + case MassUnit.LongHundredweight: return _value/0.01968413055222121; + case MassUnit.LongTon: return _value*1.0160469088e3; + case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; + case MassUnit.Megatonne: return (_value*1e3) * 1e6d; + case MassUnit.Microgram: return (_value/1e3) * 1e-6d; + case MassUnit.Milligram: return (_value/1e3) * 1e-3d; + case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; + case MassUnit.Ounce: return _value/35.2739619; + case MassUnit.Pound: return _value*0.45359237; + case MassUnit.ShortHundredweight: return _value/0.022046226218487758; + case MassUnit.ShortTon: return _value*9.0718474e2; + case MassUnit.Slug: return _value/6.852176556196105e-2; + case MassUnit.Stone: return _value/0.1574731728702698; + case MassUnit.Tonne: return _value*1e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(MassUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MassUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; + case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; + case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; + case MassUnit.Gram: return baseUnitValue*1e3; + case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; + case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; + case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; + case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; + case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; + case MassUnit.LongTon: return baseUnitValue/1.0160469088e3; + case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; + case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; + case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; + case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; + case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; + case MassUnit.Ounce: return baseUnitValue*35.2739619; + case MassUnit.Pound: return baseUnitValue/0.45359237; + case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; + case MassUnit.ShortTon: return baseUnitValue/9.0718474e2; + case MassUnit.Slug: return baseUnitValue*6.852176556196105e-2; + case MassUnit.Stone: return baseUnitValue*0.1574731728702698; + case MassUnit.Tonne: return baseUnitValue/1e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MassUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs index 2d32269db7..38d94b6ccf 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,177 +49,384 @@ namespace UnitsNet /// /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MassFlow : IComparable, IComparable + public partial struct MassFlow : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable MassFlow from nullable CentigramsPerSecond. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromCentigramsPerSecond(QuantityValue? centigramspersecond) + private readonly MassFlowUnit? _unit; + + static MassFlow() { - return centigramspersecond.HasValue ? FromCentigramsPerSecond(centigramspersecond.Value) : default(MassFlow?); + BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); } /// - /// Get nullable MassFlow from nullable DecagramsPerSecond. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromDecagramsPerSecond(QuantityValue? decagramspersecond) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MassFlow(double numericValue, MassFlowUnit unit) { - return decagramspersecond.HasValue ? FromDecagramsPerSecond(decagramspersecond.Value) : default(MassFlow?); + if(unit == MassFlowUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. + /// + public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; + + /// + /// Represents the largest possible value of MassFlow + /// + public static MassFlow MaxValue => new MassFlow(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassFlow + /// + public static MassFlow MinValue => new MassFlow(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassFlow; + + /// + /// All units of measurement for the MassFlow quantity. + /// + public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. + /// + public static MassFlow Zero => new MassFlow(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassFlow in CentigramsPerSecond. + /// + public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); + + /// + /// Get MassFlow in DecagramsPerSecond. + /// + public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); + + /// + /// Get MassFlow in DecigramsPerSecond. + /// + public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); + + /// + /// Get MassFlow in GramsPerSecond. + /// + public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); + + /// + /// Get MassFlow in HectogramsPerSecond. + /// + public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); + + /// + /// Get MassFlow in KilogramsPerHour. + /// + public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); + + /// + /// Get MassFlow in KilogramsPerMinute. + /// + public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); + + /// + /// Get MassFlow in KilogramsPerSecond. + /// + public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); + + /// + /// Get MassFlow in MegapoundsPerHour. + /// + public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); + + /// + /// Get MassFlow in MegapoundsPerMinute. + /// + public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + + /// + /// Get MassFlow in MicrogramsPerSecond. + /// + public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); + + /// + /// Get MassFlow in MilligramsPerSecond. + /// + public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); + + /// + /// Get MassFlow in NanogramsPerSecond. + /// + public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); + + /// + /// Get MassFlow in PoundsPerHour. + /// + public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); + + /// + /// Get MassFlow in PoundsPerMinute. + /// + public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + + /// + /// Get MassFlow in ShortTonsPerHour. + /// + public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); + + /// + /// Get MassFlow in TonnesPerDay. + /// + public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); + /// - /// Get nullable MassFlow from nullable DecigramsPerSecond. + /// Get MassFlow in TonnesPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromDecigramsPerSecond(QuantityValue? decigramspersecond) + public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFlowUnit unit) { - return decigramspersecond.HasValue ? FromDecigramsPerSecond(decigramspersecond.Value) : default(MassFlow?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MassFlow from nullable GramsPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromGramsPerSecond(QuantityValue? gramspersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] IFormatProvider provider) { - return gramspersecond.HasValue ? FromGramsPerSecond(gramspersecond.Value) : default(MassFlow?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable MassFlow from nullable HectogramsPerSecond. + /// Get MassFlow from CentigramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromHectogramsPerSecond(QuantityValue? hectogramspersecond) + /// If value is NaN or Infinity. + public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) { - return hectogramspersecond.HasValue ? FromHectogramsPerSecond(hectogramspersecond.Value) : default(MassFlow?); + double value = (double) centigramspersecond; + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); } - /// - /// Get nullable MassFlow from nullable KilogramsPerHour. + /// Get MassFlow from DecagramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromKilogramsPerHour(QuantityValue? kilogramsperhour) + /// If value is NaN or Infinity. + public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) { - return kilogramsperhour.HasValue ? FromKilogramsPerHour(kilogramsperhour.Value) : default(MassFlow?); + double value = (double) decagramspersecond; + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); } - /// - /// Get nullable MassFlow from nullable KilogramsPerMinute. + /// Get MassFlow from DecigramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromKilogramsPerMinute(QuantityValue? kilogramsperminute) + /// If value is NaN or Infinity. + public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) { - return kilogramsperminute.HasValue ? FromKilogramsPerMinute(kilogramsperminute.Value) : default(MassFlow?); + double value = (double) decigramspersecond; + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); } - /// - /// Get nullable MassFlow from nullable KilogramsPerSecond. + /// Get MassFlow from GramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromKilogramsPerSecond(QuantityValue? kilogramspersecond) + /// If value is NaN or Infinity. + public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) { - return kilogramspersecond.HasValue ? FromKilogramsPerSecond(kilogramspersecond.Value) : default(MassFlow?); + double value = (double) gramspersecond; + return new MassFlow(value, MassFlowUnit.GramPerSecond); } - /// - /// Get nullable MassFlow from nullable MegapoundsPerHour. + /// Get MassFlow from HectogramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromMegapoundsPerHour(QuantityValue? megapoundsperhour) + /// If value is NaN or Infinity. + public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) { - return megapoundsperhour.HasValue ? FromMegapoundsPerHour(megapoundsperhour.Value) : default(MassFlow?); + double value = (double) hectogramspersecond; + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); } - /// - /// Get nullable MassFlow from nullable MegapoundsPerMinute. + /// Get MassFlow from KilogramsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromMegapoundsPerMinute(QuantityValue? megapoundsperminute) + /// If value is NaN or Infinity. + public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) { - return megapoundsperminute.HasValue ? FromMegapoundsPerMinute(megapoundsperminute.Value) : default(MassFlow?); + double value = (double) kilogramsperhour; + return new MassFlow(value, MassFlowUnit.KilogramPerHour); } - /// - /// Get nullable MassFlow from nullable MicrogramsPerSecond. + /// Get MassFlow from KilogramsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromMicrogramsPerSecond(QuantityValue? microgramspersecond) + /// If value is NaN or Infinity. + public static MassFlow FromKilogramsPerMinute(QuantityValue kilogramsperminute) { - return microgramspersecond.HasValue ? FromMicrogramsPerSecond(microgramspersecond.Value) : default(MassFlow?); + double value = (double) kilogramsperminute; + return new MassFlow(value, MassFlowUnit.KilogramPerMinute); } - /// - /// Get nullable MassFlow from nullable MilligramsPerSecond. + /// Get MassFlow from KilogramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromMilligramsPerSecond(QuantityValue? milligramspersecond) + /// If value is NaN or Infinity. + public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) { - return milligramspersecond.HasValue ? FromMilligramsPerSecond(milligramspersecond.Value) : default(MassFlow?); + double value = (double) kilogramspersecond; + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); } - /// - /// Get nullable MassFlow from nullable NanogramsPerSecond. + /// Get MassFlow from MegapoundsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromNanogramsPerSecond(QuantityValue? nanogramspersecond) + /// If value is NaN or Infinity. + public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) { - return nanogramspersecond.HasValue ? FromNanogramsPerSecond(nanogramspersecond.Value) : default(MassFlow?); + double value = (double) megapoundsperhour; + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); } - /// - /// Get nullable MassFlow from nullable PoundsPerHour. + /// Get MassFlow from MegapoundsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromPoundsPerHour(QuantityValue? poundsperhour) + /// If value is NaN or Infinity. + public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute) { - return poundsperhour.HasValue ? FromPoundsPerHour(poundsperhour.Value) : default(MassFlow?); + double value = (double) megapoundsperminute; + return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); } - /// - /// Get nullable MassFlow from nullable PoundsPerMinute. + /// Get MassFlow from MicrogramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromPoundsPerMinute(QuantityValue? poundsperminute) + /// If value is NaN or Infinity. + public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) { - return poundsperminute.HasValue ? FromPoundsPerMinute(poundsperminute.Value) : default(MassFlow?); + double value = (double) microgramspersecond; + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); } - /// - /// Get nullable MassFlow from nullable ShortTonsPerHour. + /// Get MassFlow from MilligramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromShortTonsPerHour(QuantityValue? shorttonsperhour) + /// If value is NaN or Infinity. + public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) { - return shorttonsperhour.HasValue ? FromShortTonsPerHour(shorttonsperhour.Value) : default(MassFlow?); + double value = (double) milligramspersecond; + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); } - /// - /// Get nullable MassFlow from nullable TonnesPerDay. + /// Get MassFlow from NanogramsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromTonnesPerDay(QuantityValue? tonnesperday) + /// If value is NaN or Infinity. + public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) { - return tonnesperday.HasValue ? FromTonnesPerDay(tonnesperday.Value) : default(MassFlow?); + double value = (double) nanogramspersecond; + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); } - /// - /// Get nullable MassFlow from nullable TonnesPerHour. + /// Get MassFlow from PoundsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlow? FromTonnesPerHour(QuantityValue? tonnesperhour) + /// If value is NaN or Infinity. + public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) { - return tonnesperhour.HasValue ? FromTonnesPerHour(tonnesperhour.Value) : default(MassFlow?); + double value = (double) poundsperhour; + return new MassFlow(value, MassFlowUnit.PoundPerHour); + } + /// + /// Get MassFlow from PoundsPerMinute. + /// + /// If value is NaN or Infinity. + public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) + { + double value = (double) poundsperminute; + return new MassFlow(value, MassFlowUnit.PoundPerMinute); + } + /// + /// Get MassFlow from ShortTonsPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) + { + double value = (double) shorttonsperhour; + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); + } + /// + /// Get MassFlow from TonnesPerDay. + /// + /// If value is NaN or Infinity. + public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) + { + double value = (double) tonnesperday; + return new MassFlow(value, MassFlowUnit.TonnePerDay); + } + /// + /// Get MassFlow from TonnesPerHour. + /// + /// If value is NaN or Infinity. + public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) + { + double value = (double) tonnesperhour; + return new MassFlow(value, MassFlowUnit.TonnePerHour); } /// @@ -230,28 +435,156 @@ public partial struct MassFlow : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MassFlow unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlow? From(QuantityValue? value, MassFlowUnit fromUnit) + public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) { - return value.HasValue ? new MassFlow((double)value.Value, fromUnit) : default(MassFlow?); + return new MassFlow((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MassFlow Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlow result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MassFlowUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MassFlowUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MassFlowUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MassFlow operator -(MassFlow right) @@ -291,6 +624,8 @@ public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(MassFlow left, MassFlow right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -311,180 +646,250 @@ public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MassFlow left, MassFlow right) + public static bool operator ==(MassFlow left, MassFlow right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MassFlow left, MassFlow right) + public static bool operator !=(MassFlow left, MassFlow right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MassFlow other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlow Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassFlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromGramsPerSecond(x.GramsPerSecond + y.GramsPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlow result) + /// A hash code for the current MassFlow. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MassFlow); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFlowUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MassFlow to another MassFlow with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MassFlow with the specified unit. + public MassFlow ToUnit(MassFlowUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MassFlow(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFlowUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; + case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; + case MassFlowUnit.GramPerSecond: return _value; + case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; + case MassFlowUnit.KilogramPerHour: return _value/3.6; + case MassFlowUnit.KilogramPerMinute: return _value/0.06; + case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; + case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; + case MassFlowUnit.MegapoundPerMinute: return (_value/0.132277) * 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; + case MassFlowUnit.PoundPerHour: return _value/7.93664; + case MassFlowUnit.PoundPerMinute: return _value/0.132277; + case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; + case MassFlowUnit.TonnePerDay: return _value/0.0864000; + case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(MassFlowUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - if (unit == MassFlowUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; + case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; + case MassFlowUnit.GramPerSecond: return baseUnitValue; + case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; + case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; + case MassFlowUnit.KilogramPerMinute: return baseUnitValue*0.06; + case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; + case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; + case MassFlowUnit.MegapoundPerMinute: return (baseUnitValue*0.132277) / 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; + case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; + case MassFlowUnit.PoundPerMinute: return baseUnitValue*0.132277; + case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; + case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; + case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MassFlowUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs index 032190a63c..6e77cad9f0 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// Mass flux is the mass flow rate per unit area. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MassFlux : IComparable, IComparable + public partial struct MassFlux : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFluxUnit? _unit; + + static MassFlux() + { + BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MassFlux(double numericValue, MassFluxUnit unit) + { + if(unit == MassFluxUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. + /// + public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; + + /// + /// Represents the largest possible value of MassFlux + /// + public static MassFlux MaxValue => new MassFlux(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassFlux + /// + public static MassFlux MinValue => new MassFlux(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassFlux; + + /// + /// All units of measurement for the MassFlux quantity. + /// + public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// + public static MassFlux Zero => new MassFlux(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassFlux.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassFlux.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable MassFlux from nullable GramsPerSecondPerSquareMeter. + /// Get MassFlux in GramsPerSecondPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlux? FromGramsPerSecondPerSquareMeter(QuantityValue? gramspersecondpersquaremeter) + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + + /// + /// Get MassFlux in KilogramsPerSecondPerSquareMeter. + /// + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassFluxUnit unit) { - return gramspersecondpersquaremeter.HasValue ? FromGramsPerSecondPerSquareMeter(gramspersecondpersquaremeter.Value) : default(MassFlux?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MassFlux from nullable KilogramsPerSecondPerSquareMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassFlux? FromKilogramsPerSecondPerSquareMeter(QuantityValue? kilogramspersecondpersquaremeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] IFormatProvider provider) { - return kilogramspersecondpersquaremeter.HasValue ? FromKilogramsPerSecondPerSquareMeter(kilogramspersecondpersquaremeter.Value) : default(MassFlux?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get MassFlux from GramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) + { + double value = (double) gramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); + } + /// + /// Get MassFlux from KilogramsPerSecondPerSquareMeter. + /// + /// If value is NaN or Infinity. + public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) + { + double value = (double) kilogramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); } /// @@ -86,28 +211,156 @@ public partial struct MassFlux : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MassFlux unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassFlux? From(QuantityValue? value, MassFluxUnit fromUnit) + public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) { - return value.HasValue ? new MassFlux((double)value.Value, fromUnit) : default(MassFlux?); + return new MassFlux((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MassFlux Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassFlux result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlux result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MassFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MassFluxUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MassFluxUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MassFlux operator -(MassFlux right) @@ -147,6 +400,8 @@ public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(MassFlux left, MassFlux right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -167,180 +422,218 @@ public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MassFlux left, MassFlux right) + public static bool operator ==(MassFlux left, MassFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassFlux, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MassFlux left, MassFlux right) + public static bool operator !=(MassFlux left, MassFlux right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MassFlux other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlux Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassFluxUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerSecondPerSquareMeter(x.KilogramsPerSecondPerSquareMeter + y.KilogramsPerSecondPerSquareMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassFlux result) + /// A hash code for the current MassFlux. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MassFlux); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFluxUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MassFlux to another MassFlux with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MassFlux with the specified unit. + public MassFlux ToUnit(MassFluxUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MassFlux(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFluxUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(MassFluxUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MassFluxUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFluxUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MassFluxUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs index dc0ce82630..8a99f8e914 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,267 +49,524 @@ namespace UnitsNet /// /// A property of body reflects how its mass is distributed with regard to an axis. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MassMomentOfInertia : IComparable, IComparable + public partial struct MassMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable MassMomentOfInertia from nullable GramSquareCentimeters. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromGramSquareCentimeters(QuantityValue? gramsquarecentimeters) + private readonly MassMomentOfInertiaUnit? _unit; + + static MassMomentOfInertia() { - return gramsquarecentimeters.HasValue ? FromGramSquareCentimeters(gramsquarecentimeters.Value) : default(MassMomentOfInertia?); + BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); } /// - /// Get nullable MassMomentOfInertia from nullable GramSquareDecimeters. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromGramSquareDecimeters(QuantityValue? gramsquaredecimeters) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MassMomentOfInertia(double numericValue, MassMomentOfInertiaUnit unit) { - return gramsquaredecimeters.HasValue ? FromGramSquareDecimeters(gramsquaredecimeters.Value) : default(MassMomentOfInertia?); + if(unit == MassMomentOfInertiaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. + /// + public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; + + /// + /// Represents the largest possible value of MassMomentOfInertia + /// + public static MassMomentOfInertia MaxValue => new MassMomentOfInertia(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MassMomentOfInertia + /// + public static MassMomentOfInertia MinValue => new MassMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MassMomentOfInertia; + + /// + /// All units of measurement for the MassMomentOfInertia quantity. + /// + public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. + /// + public static MassMomentOfInertia Zero => new MassMomentOfInertia(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MassMomentOfInertia.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MassMomentOfInertia in GramSquareCentimeters. + /// + public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in GramSquareDecimeters. + /// + public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in GramSquareMeters. + /// + public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); + + /// + /// Get MassMomentOfInertia in GramSquareMillimeters. + /// + public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareCentimeters. + /// + public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareDecimeters. + /// + public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareMeters. + /// + public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); + + /// + /// Get MassMomentOfInertia in KilogramSquareMillimeters. + /// + public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareCentimeters. + /// + public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareDecimeters. + /// + public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareMeters. + /// + public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); + + /// + /// Get MassMomentOfInertia in KilotonneSquareMilimeters. + /// + public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareCentimeters. + /// + public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareDecimeters. + /// + public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareMeters. + /// + public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); + + /// + /// Get MassMomentOfInertia in MegatonneSquareMilimeters. + /// + public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + /// - /// Get nullable MassMomentOfInertia from nullable GramSquareMeters. + /// Get MassMomentOfInertia in MilligramSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromGramSquareMeters(QuantityValue? gramsquaremeters) + public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareDecimeters. + /// + public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareMeters. + /// + public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); + + /// + /// Get MassMomentOfInertia in MilligramSquareMillimeters. + /// + public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); + + /// + /// Get MassMomentOfInertia in PoundSquareFeet. + /// + public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); + + /// + /// Get MassMomentOfInertia in PoundSquareInches. + /// + public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); + + /// + /// Get MassMomentOfInertia in SlugSquareFeet. + /// + public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); + + /// + /// Get MassMomentOfInertia in SlugSquareInches. + /// + public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); + + /// + /// Get MassMomentOfInertia in TonneSquareCentimeters. + /// + public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); + + /// + /// Get MassMomentOfInertia in TonneSquareDecimeters. + /// + public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); + + /// + /// Get MassMomentOfInertia in TonneSquareMeters. + /// + public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); + + /// + /// Get MassMomentOfInertia in TonneSquareMilimeters. + /// + public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MassMomentOfInertiaUnit unit) { - return gramsquaremeters.HasValue ? FromGramSquareMeters(gramsquaremeters.Value) : default(MassMomentOfInertia?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MassMomentOfInertia from nullable GramSquareMillimeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromGramSquareMillimeters(QuantityValue? gramsquaremillimeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) { - return gramsquaremillimeters.HasValue ? FromGramSquareMillimeters(gramsquaremillimeters.Value) : default(MassMomentOfInertia?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable MassMomentOfInertia from nullable KilogramSquareCentimeters. + /// Get MassMomentOfInertia from GramSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilogramSquareCentimeters(QuantityValue? kilogramsquarecentimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) { - return kilogramsquarecentimeters.HasValue ? FromKilogramSquareCentimeters(kilogramsquarecentimeters.Value) : default(MassMomentOfInertia?); + double value = (double) gramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilogramSquareDecimeters. + /// Get MassMomentOfInertia from GramSquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilogramSquareDecimeters(QuantityValue? kilogramsquaredecimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) { - return kilogramsquaredecimeters.HasValue ? FromKilogramSquareDecimeters(kilogramsquaredecimeters.Value) : default(MassMomentOfInertia?); + double value = (double) gramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilogramSquareMeters. + /// Get MassMomentOfInertia from GramSquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilogramSquareMeters(QuantityValue? kilogramsquaremeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) { - return kilogramsquaremeters.HasValue ? FromKilogramSquareMeters(kilogramsquaremeters.Value) : default(MassMomentOfInertia?); + double value = (double) gramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilogramSquareMillimeters. + /// Get MassMomentOfInertia from GramSquareMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilogramSquareMillimeters(QuantityValue? kilogramsquaremillimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) { - return kilogramsquaremillimeters.HasValue ? FromKilogramSquareMillimeters(kilogramsquaremillimeters.Value) : default(MassMomentOfInertia?); + double value = (double) gramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilotonneSquareCentimeters. + /// Get MassMomentOfInertia from KilogramSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilotonneSquareCentimeters(QuantityValue? kilotonnesquarecentimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) { - return kilotonnesquarecentimeters.HasValue ? FromKilotonneSquareCentimeters(kilotonnesquarecentimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilogramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilotonneSquareDecimeters. + /// Get MassMomentOfInertia from KilogramSquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilotonneSquareDecimeters(QuantityValue? kilotonnesquaredecimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) { - return kilotonnesquaredecimeters.HasValue ? FromKilotonneSquareDecimeters(kilotonnesquaredecimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilogramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilotonneSquareMeters. + /// Get MassMomentOfInertia from KilogramSquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilotonneSquareMeters(QuantityValue? kilotonnesquaremeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) { - return kilotonnesquaremeters.HasValue ? FromKilotonneSquareMeters(kilotonnesquaremeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilogramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); } - /// - /// Get nullable MassMomentOfInertia from nullable KilotonneSquareMilimeters. + /// Get MassMomentOfInertia from KilogramSquareMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromKilotonneSquareMilimeters(QuantityValue? kilotonnesquaremilimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) { - return kilotonnesquaremilimeters.HasValue ? FromKilotonneSquareMilimeters(kilotonnesquaremilimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilogramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MegatonneSquareCentimeters. + /// Get MassMomentOfInertia from KilotonneSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMegatonneSquareCentimeters(QuantityValue? megatonnesquarecentimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) { - return megatonnesquarecentimeters.HasValue ? FromMegatonneSquareCentimeters(megatonnesquarecentimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilotonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MegatonneSquareDecimeters. + /// Get MassMomentOfInertia from KilotonneSquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMegatonneSquareDecimeters(QuantityValue? megatonnesquaredecimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) { - return megatonnesquaredecimeters.HasValue ? FromMegatonneSquareDecimeters(megatonnesquaredecimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilotonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MegatonneSquareMeters. + /// Get MassMomentOfInertia from KilotonneSquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMegatonneSquareMeters(QuantityValue? megatonnesquaremeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) { - return megatonnesquaremeters.HasValue ? FromMegatonneSquareMeters(megatonnesquaremeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilotonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MegatonneSquareMilimeters. + /// Get MassMomentOfInertia from KilotonneSquareMilimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMegatonneSquareMilimeters(QuantityValue? megatonnesquaremilimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) { - return megatonnesquaremilimeters.HasValue ? FromMegatonneSquareMilimeters(megatonnesquaremilimeters.Value) : default(MassMomentOfInertia?); + double value = (double) kilotonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MilligramSquareCentimeters. + /// Get MassMomentOfInertia from MegatonneSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMilligramSquareCentimeters(QuantityValue? milligramsquarecentimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) { - return milligramsquarecentimeters.HasValue ? FromMilligramSquareCentimeters(milligramsquarecentimeters.Value) : default(MassMomentOfInertia?); + double value = (double) megatonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MilligramSquareDecimeters. + /// Get MassMomentOfInertia from MegatonneSquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMilligramSquareDecimeters(QuantityValue? milligramsquaredecimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) { - return milligramsquaredecimeters.HasValue ? FromMilligramSquareDecimeters(milligramsquaredecimeters.Value) : default(MassMomentOfInertia?); + double value = (double) megatonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MilligramSquareMeters. + /// Get MassMomentOfInertia from MegatonneSquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMilligramSquareMeters(QuantityValue? milligramsquaremeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) { - return milligramsquaremeters.HasValue ? FromMilligramSquareMeters(milligramsquaremeters.Value) : default(MassMomentOfInertia?); + double value = (double) megatonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); } - /// - /// Get nullable MassMomentOfInertia from nullable MilligramSquareMillimeters. + /// Get MassMomentOfInertia from MegatonneSquareMilimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromMilligramSquareMillimeters(QuantityValue? milligramsquaremillimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) { - return milligramsquaremillimeters.HasValue ? FromMilligramSquareMillimeters(milligramsquaremillimeters.Value) : default(MassMomentOfInertia?); + double value = (double) megatonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable PoundSquareFeet. + /// Get MassMomentOfInertia from MilligramSquareCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromPoundSquareFeet(QuantityValue? poundsquarefeet) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) { - return poundsquarefeet.HasValue ? FromPoundSquareFeet(poundsquarefeet.Value) : default(MassMomentOfInertia?); + double value = (double) milligramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable PoundSquareInches. + /// Get MassMomentOfInertia from MilligramSquareDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromPoundSquareInches(QuantityValue? poundsquareinches) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) { - return poundsquareinches.HasValue ? FromPoundSquareInches(poundsquareinches.Value) : default(MassMomentOfInertia?); + double value = (double) milligramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable SlugSquareFeet. + /// Get MassMomentOfInertia from MilligramSquareMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromSlugSquareFeet(QuantityValue? slugsquarefeet) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) { - return slugsquarefeet.HasValue ? FromSlugSquareFeet(slugsquarefeet.Value) : default(MassMomentOfInertia?); + double value = (double) milligramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); } - /// - /// Get nullable MassMomentOfInertia from nullable SlugSquareInches. + /// Get MassMomentOfInertia from MilligramSquareMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromSlugSquareInches(QuantityValue? slugsquareinches) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) { - return slugsquareinches.HasValue ? FromSlugSquareInches(slugsquareinches.Value) : default(MassMomentOfInertia?); + double value = (double) milligramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); } - /// - /// Get nullable MassMomentOfInertia from nullable TonneSquareCentimeters. + /// Get MassMomentOfInertia from PoundSquareFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromTonneSquareCentimeters(QuantityValue? tonnesquarecentimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) { - return tonnesquarecentimeters.HasValue ? FromTonneSquareCentimeters(tonnesquarecentimeters.Value) : default(MassMomentOfInertia?); + double value = (double) poundsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); } - /// - /// Get nullable MassMomentOfInertia from nullable TonneSquareDecimeters. + /// Get MassMomentOfInertia from PoundSquareInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromTonneSquareDecimeters(QuantityValue? tonnesquaredecimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) { - return tonnesquaredecimeters.HasValue ? FromTonneSquareDecimeters(tonnesquaredecimeters.Value) : default(MassMomentOfInertia?); + double value = (double) poundsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); } - /// - /// Get nullable MassMomentOfInertia from nullable TonneSquareMeters. + /// Get MassMomentOfInertia from SlugSquareFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromTonneSquareMeters(QuantityValue? tonnesquaremeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) { - return tonnesquaremeters.HasValue ? FromTonneSquareMeters(tonnesquaremeters.Value) : default(MassMomentOfInertia?); + double value = (double) slugsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); } - /// - /// Get nullable MassMomentOfInertia from nullable TonneSquareMilimeters. + /// Get MassMomentOfInertia from SlugSquareInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MassMomentOfInertia? FromTonneSquareMilimeters(QuantityValue? tonnesquaremilimeters) + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) { - return tonnesquaremilimeters.HasValue ? FromTonneSquareMilimeters(tonnesquaremilimeters.Value) : default(MassMomentOfInertia?); + double value = (double) slugsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); + } + /// + /// Get MassMomentOfInertia from TonneSquareCentimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) + { + double value = (double) tonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareDecimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) + { + double value = (double) tonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) + { + double value = (double) tonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); + } + /// + /// Get MassMomentOfInertia from TonneSquareMilimeters. + /// + /// If value is NaN or Infinity. + public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) + { + double value = (double) tonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); } /// @@ -320,28 +575,156 @@ public partial struct MassMomentOfInertia : IComparable, IComparableValue to convert from. /// Unit to convert from. /// MassMomentOfInertia unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MassMomentOfInertia? From(QuantityValue? value, MassMomentOfInertiaUnit fromUnit) + public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) { - return value.HasValue ? new MassMomentOfInertia((double)value.Value, fromUnit) : default(MassMomentOfInertia?); + return new MassMomentOfInertia((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MassMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassMomentOfInertia result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MassMomentOfInertiaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MassMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MassMomentOfInertia operator -(MassMomentOfInertia right) @@ -381,6 +764,8 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(MassMomentOfInertia left, MassMomentOfInertia right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -401,180 +786,270 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) + public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Equals(right); + } + + public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MassMomentOfInertia, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(MassMomentOfInertia other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassMomentOfInertia Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MassMomentOfInertiaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramSquareMeters(x.KilogramSquareMeters + y.KilogramSquareMeters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MassMomentOfInertia result) + /// A hash code for the current MassMomentOfInertia. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MassMomentOfInertia); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassMomentOfInertiaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MassMomentOfInertia with the specified unit. + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MassMomentOfInertia(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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 unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MassMomentOfInertiaUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassMomentOfInertiaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs index 3b639e0de9..a1e0c9befd 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// Molar energy is the amount of energy stored in 1 mole of a substance. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MolarEnergy : IComparable, IComparable + public partial struct MolarEnergy : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEnergyUnit? _unit; + + static MolarEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MolarEnergy(double numericValue, MolarEnergyUnit unit) + { + if(unit == MolarEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. + /// + public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; + + /// + /// Represents the largest possible value of MolarEnergy + /// + public static MolarEnergy MaxValue => new MolarEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarEnergy + /// + public static MolarEnergy MinValue => new MolarEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarEnergy; + + /// + /// All units of measurement for the MolarEnergy quantity. + /// + public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. + /// + public static MolarEnergy Zero => new MolarEnergy(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable MolarEnergy from nullable JoulesPerMole. + /// Get MolarEnergy in JoulesPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEnergy? FromJoulesPerMole(QuantityValue? joulespermole) + public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); + + /// + /// Get MolarEnergy in KilojoulesPerMole. + /// + public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); + + /// + /// Get MolarEnergy in MegajoulesPerMole. + /// + public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEnergyUnit unit) { - return joulespermole.HasValue ? FromJoulesPerMole(joulespermole.Value) : default(MolarEnergy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MolarEnergy from nullable KilojoulesPerMole. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEnergy? FromKilojoulesPerMole(QuantityValue? kilojoulespermole) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider) { - return kilojoulespermole.HasValue ? FromKilojoulesPerMole(kilojoulespermole.Value) : default(MolarEnergy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEnergy from JoulesPerMole. + /// + /// If value is NaN or Infinity. + public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) + { + double value = (double) joulespermole; + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); + } /// - /// Get nullable MolarEnergy from nullable MegajoulesPerMole. + /// Get MolarEnergy from KilojoulesPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEnergy? FromMegajoulesPerMole(QuantityValue? megajoulespermole) + /// If value is NaN or Infinity. + public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) { - return megajoulespermole.HasValue ? FromMegajoulesPerMole(megajoulespermole.Value) : default(MolarEnergy?); + double value = (double) kilojoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); + } + /// + /// Get MolarEnergy from MegajoulesPerMole. + /// + /// If value is NaN or Infinity. + public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) + { + double value = (double) megajoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); } /// @@ -95,28 +225,156 @@ public partial struct MolarEnergy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MolarEnergy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEnergy? From(QuantityValue? value, MolarEnergyUnit fromUnit) + public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) { - return value.HasValue ? new MolarEnergy((double)value.Value, fromUnit) : default(MolarEnergy?); + return new MolarEnergy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolarEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MolarEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MolarEnergy operator -(MolarEnergy right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] IFormatPr #endregion + #region Equality / IComparable + public static bool operator <=(MolarEnergy left, MolarEnergy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] IFormatPr return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MolarEnergy left, MolarEnergy right) + public static bool operator ==(MolarEnergy left, MolarEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MolarEnergy left, MolarEnergy right) + public static bool operator !=(MolarEnergy left, MolarEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MolarEnergy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MolarEnergy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerMole(x.JoulesPerMole + y.JoulesPerMole)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEnergy result) + /// A hash code for the current MolarEnergy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MolarEnergy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MolarEnergy to another MolarEnergy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MolarEnergy with the specified unit. + public MolarEnergy ToUnit(MolarEnergyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MolarEnergy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MolarEnergyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs index 797d847c54..807f2ef8b4 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MolarEntropy : IComparable, IComparable + public partial struct MolarEntropy : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEntropyUnit? _unit; + + static MolarEntropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MolarEntropy(double numericValue, MolarEntropyUnit unit) + { + if(unit == MolarEntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. + /// + public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; + + /// + /// Represents the largest possible value of MolarEntropy + /// + public static MolarEntropy MaxValue => new MolarEntropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarEntropy + /// + public static MolarEntropy MinValue => new MolarEntropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarEntropy; + + /// + /// All units of measurement for the MolarEntropy quantity. + /// + public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// + public static MolarEntropy Zero => new MolarEntropy(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable MolarEntropy from nullable JoulesPerMoleKelvin. + /// Get MolarEntropy in JoulesPerMoleKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEntropy? FromJoulesPerMoleKelvin(QuantityValue? joulespermolekelvin) + public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); + + /// + /// Get MolarEntropy in KilojoulesPerMoleKelvin. + /// + public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); + + /// + /// Get MolarEntropy in MegajoulesPerMoleKelvin. + /// + public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarEntropyUnit unit) { - return joulespermolekelvin.HasValue ? FromJoulesPerMoleKelvin(joulespermolekelvin.Value) : default(MolarEntropy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MolarEntropy from nullable KilojoulesPerMoleKelvin. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEntropy? FromKilojoulesPerMoleKelvin(QuantityValue? kilojoulespermolekelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider) { - return kilojoulespermolekelvin.HasValue ? FromKilojoulesPerMoleKelvin(kilojoulespermolekelvin.Value) : default(MolarEntropy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get MolarEntropy from JoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) + { + double value = (double) joulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); + } /// - /// Get nullable MolarEntropy from nullable MegajoulesPerMoleKelvin. + /// Get MolarEntropy from KilojoulesPerMoleKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarEntropy? FromMegajoulesPerMoleKelvin(QuantityValue? megajoulespermolekelvin) + /// If value is NaN or Infinity. + public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) { - return megajoulespermolekelvin.HasValue ? FromMegajoulesPerMoleKelvin(megajoulespermolekelvin.Value) : default(MolarEntropy?); + double value = (double) kilojoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); + } + /// + /// Get MolarEntropy from MegajoulesPerMoleKelvin. + /// + /// If value is NaN or Infinity. + public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) + { + double value = (double) megajoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); } /// @@ -95,28 +225,156 @@ public partial struct MolarEntropy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MolarEntropy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarEntropy? From(QuantityValue? value, MolarEntropyUnit fromUnit) + public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) { - return value.HasValue ? new MolarEntropy((double)value.Value, fromUnit) : default(MolarEntropy?); + return new MolarEntropy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEntropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolarEntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MolarEntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MolarEntropy operator -(MolarEntropy right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(MolarEntropy left, MolarEntropy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MolarEntropy left, MolarEntropy right) + public static bool operator ==(MolarEntropy left, MolarEntropy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MolarEntropy left, MolarEntropy right) + public static bool operator !=(MolarEntropy left, MolarEntropy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MolarEntropy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarEntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerMoleKelvin(x.JoulesPerMoleKelvin + y.JoulesPerMoleKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarEntropy result) + /// A hash code for the current MolarEntropy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MolarEntropy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MolarEntropy to another MolarEntropy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MolarEntropy with the specified unit. + public MolarEntropy ToUnit(MolarEntropyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MolarEntropy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MolarEntropyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs index ddb2f3dc88..a9ac972482 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,123 +49,300 @@ namespace UnitsNet /// /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct MolarMass : IComparable, IComparable + public partial struct MolarMass : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable MolarMass from nullable CentigramsPerMole. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromCentigramsPerMole(QuantityValue? centigramspermole) + private readonly MolarMassUnit? _unit; + + static MolarMass() { - return centigramspermole.HasValue ? FromCentigramsPerMole(centigramspermole.Value) : default(MolarMass?); + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); } /// - /// Get nullable MolarMass from nullable DecagramsPerMole. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromDecagramsPerMole(QuantityValue? decagramspermole) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public MolarMass(double numericValue, MolarMassUnit unit) { - return decagramspermole.HasValue ? FromDecagramsPerMole(decagramspermole.Value) : default(MolarMass?); + if(unit == MolarMassUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. + /// + public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; + + /// + /// Represents the largest possible value of MolarMass + /// + public static MolarMass MaxValue => new MolarMass(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of MolarMass + /// + public static MolarMass MinValue => new MolarMass(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.MolarMass; + + /// + /// All units of measurement for the MolarMass quantity. + /// + public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. + /// + public static MolarMass Zero => new MolarMass(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => MolarMass.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => MolarMass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get MolarMass in CentigramsPerMole. + /// + public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); + + /// + /// Get MolarMass in DecagramsPerMole. + /// + public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); + + /// + /// Get MolarMass in DecigramsPerMole. + /// + public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); + + /// + /// Get MolarMass in GramsPerMole. + /// + public double GramsPerMole => As(MolarMassUnit.GramPerMole); + + /// + /// Get MolarMass in HectogramsPerMole. + /// + public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); + + /// + /// Get MolarMass in KilogramsPerMole. + /// + public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); + + /// + /// Get MolarMass in KilopoundsPerMole. + /// + public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); + + /// + /// Get MolarMass in MegapoundsPerMole. + /// + public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); + + /// + /// Get MolarMass in MicrogramsPerMole. + /// + public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); + + /// + /// Get MolarMass in MilligramsPerMole. + /// + public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); + + /// + /// Get MolarMass in NanogramsPerMole. + /// + public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); + + /// + /// Get MolarMass in PoundsPerMole. + /// + public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); + + #endregion + + #region Static Methods + /// - /// Get nullable MolarMass from nullable DecigramsPerMole. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromDecigramsPerMole(QuantityValue? decigramspermole) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarMassUnit unit) { - return decigramspermole.HasValue ? FromDecigramsPerMole(decigramspermole.Value) : default(MolarMass?); + return GetAbbreviation(unit, null); } /// - /// Get nullable MolarMass from nullable GramsPerMole. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromGramsPerMole(QuantityValue? gramspermole) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] IFormatProvider provider) { - return gramspermole.HasValue ? FromGramsPerMole(gramspermole.Value) : default(MolarMass?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable MolarMass from nullable HectogramsPerMole. + /// Get MolarMass from CentigramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromHectogramsPerMole(QuantityValue? hectogramspermole) + /// If value is NaN or Infinity. + public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) { - return hectogramspermole.HasValue ? FromHectogramsPerMole(hectogramspermole.Value) : default(MolarMass?); + double value = (double) centigramspermole; + return new MolarMass(value, MolarMassUnit.CentigramPerMole); } - /// - /// Get nullable MolarMass from nullable KilogramsPerMole. + /// Get MolarMass from DecagramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromKilogramsPerMole(QuantityValue? kilogramspermole) + /// If value is NaN or Infinity. + public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) { - return kilogramspermole.HasValue ? FromKilogramsPerMole(kilogramspermole.Value) : default(MolarMass?); + double value = (double) decagramspermole; + return new MolarMass(value, MolarMassUnit.DecagramPerMole); } - /// - /// Get nullable MolarMass from nullable KilopoundsPerMole. + /// Get MolarMass from DecigramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromKilopoundsPerMole(QuantityValue? kilopoundspermole) + /// If value is NaN or Infinity. + public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) { - return kilopoundspermole.HasValue ? FromKilopoundsPerMole(kilopoundspermole.Value) : default(MolarMass?); + double value = (double) decigramspermole; + return new MolarMass(value, MolarMassUnit.DecigramPerMole); } - /// - /// Get nullable MolarMass from nullable MegapoundsPerMole. + /// Get MolarMass from GramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromMegapoundsPerMole(QuantityValue? megapoundspermole) + /// If value is NaN or Infinity. + public static MolarMass FromGramsPerMole(QuantityValue gramspermole) { - return megapoundspermole.HasValue ? FromMegapoundsPerMole(megapoundspermole.Value) : default(MolarMass?); + double value = (double) gramspermole; + return new MolarMass(value, MolarMassUnit.GramPerMole); } - /// - /// Get nullable MolarMass from nullable MicrogramsPerMole. + /// Get MolarMass from HectogramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromMicrogramsPerMole(QuantityValue? microgramspermole) + /// If value is NaN or Infinity. + public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) { - return microgramspermole.HasValue ? FromMicrogramsPerMole(microgramspermole.Value) : default(MolarMass?); + double value = (double) hectogramspermole; + return new MolarMass(value, MolarMassUnit.HectogramPerMole); } - /// - /// Get nullable MolarMass from nullable MilligramsPerMole. + /// Get MolarMass from KilogramsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromMilligramsPerMole(QuantityValue? milligramspermole) + /// If value is NaN or Infinity. + public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) { - return milligramspermole.HasValue ? FromMilligramsPerMole(milligramspermole.Value) : default(MolarMass?); + double value = (double) kilogramspermole; + return new MolarMass(value, MolarMassUnit.KilogramPerMole); } - /// - /// Get nullable MolarMass from nullable NanogramsPerMole. + /// Get MolarMass from KilopoundsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromNanogramsPerMole(QuantityValue? nanogramspermole) + /// If value is NaN or Infinity. + public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) { - return nanogramspermole.HasValue ? FromNanogramsPerMole(nanogramspermole.Value) : default(MolarMass?); + double value = (double) kilopoundspermole; + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); + } + /// + /// Get MolarMass from MegapoundsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) + { + double value = (double) megapoundspermole; + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); + } + /// + /// Get MolarMass from MicrogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) + { + double value = (double) microgramspermole; + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); + } + /// + /// Get MolarMass from MilligramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) + { + double value = (double) milligramspermole; + return new MolarMass(value, MolarMassUnit.MilligramPerMole); + } + /// + /// Get MolarMass from NanogramsPerMole. + /// + /// If value is NaN or Infinity. + public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) + { + double value = (double) nanogramspermole; + return new MolarMass(value, MolarMassUnit.NanogramPerMole); } - /// - /// Get nullable MolarMass from nullable PoundsPerMole. + /// Get MolarMass from PoundsPerMole. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static MolarMass? FromPoundsPerMole(QuantityValue? poundspermole) + /// If value is NaN or Infinity. + public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) { - return poundspermole.HasValue ? FromPoundsPerMole(poundspermole.Value) : default(MolarMass?); + double value = (double) poundspermole; + return new MolarMass(value, MolarMassUnit.PoundPerMole); } /// @@ -176,28 +351,156 @@ public partial struct MolarMass : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// MolarMass unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static MolarMass? From(QuantityValue? value, MolarMassUnit fromUnit) + public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) { - return value.HasValue ? new MolarMass((double)value.Value, fromUnit) : default(MolarMass?); + return new MolarMass((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarMass Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out MolarMass result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarMass result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolarMassUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarMassUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarMassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MolarMassUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static MolarMass operator -(MolarMass right) @@ -237,6 +540,8 @@ public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] IFormatProv #endregion + #region Equality / IComparable + public static bool operator <=(MolarMass left, MolarMass right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -257,180 +562,238 @@ public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] IFormatProv return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarMass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(MolarMass left, MolarMass right) + public static bool operator ==(MolarMass left, MolarMass right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(MolarMass, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(MolarMass left, MolarMass right) + public static bool operator !=(MolarMass left, MolarMass right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(MolarMass other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarMass Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarMassUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKilogramsPerMole(x.KilogramsPerMole + y.KilogramsPerMole)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out MolarMass result) + /// A hash code for the current MolarMass. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(MolarMass); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarMassUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this MolarMass to another MolarMass with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A MolarMass with the specified unit. + public MolarMass ToUnit(MolarMassUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new MolarMass(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarMassUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(MolarMassUnit unit) + { + if(Unit == unit) + return _value; - if (unit == MolarMassUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarMassUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MolarMassUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs index a21a03075b..c3bb500b58 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,247 @@ namespace UnitsNet /// /// Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Molarity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Molar_concentration + /// + public partial struct Molarity : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Molarity from nullable CentimolesPerLiter. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromCentimolesPerLiter(QuantityValue? centimolesperliter) + private readonly MolarityUnit? _unit; + + static Molarity() { - return centimolesperliter.HasValue ? FromCentimolesPerLiter(centimolesperliter.Value) : default(Molarity?); + BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); } /// - /// Get nullable Molarity from nullable DecimolesPerLiter. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromDecimolesPerLiter(QuantityValue? decimolesperliter) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Molarity(double numericValue, MolarityUnit unit) { - return decimolesperliter.HasValue ? FromDecimolesPerLiter(decimolesperliter.Value) : default(Molarity?); + if(unit == MolarityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. + /// + public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; + + /// + /// Represents the largest possible value of Molarity + /// + public static Molarity MaxValue => new Molarity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Molarity + /// + public static Molarity MinValue => new Molarity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Molarity; + + /// + /// All units of measurement for the Molarity quantity. + /// + public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. + /// + public static Molarity Zero => new Molarity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable Molarity from nullable MicromolesPerLiter. + /// The of this quantity. + /// + public QuantityType Type => Molarity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Molarity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Molarity in CentimolesPerLiter. + /// + public double CentimolesPerLiter => As(MolarityUnit.CentimolesPerLiter); + + /// + /// Get Molarity in DecimolesPerLiter. + /// + public double DecimolesPerLiter => As(MolarityUnit.DecimolesPerLiter); + + /// + /// Get Molarity in MicromolesPerLiter. + /// + public double MicromolesPerLiter => As(MolarityUnit.MicromolesPerLiter); + + /// + /// Get Molarity in MillimolesPerLiter. + /// + public double MillimolesPerLiter => As(MolarityUnit.MillimolesPerLiter); + + /// + /// Get Molarity in MolesPerCubicMeter. + /// + public double MolesPerCubicMeter => As(MolarityUnit.MolesPerCubicMeter); + + /// + /// Get Molarity in MolesPerLiter. + /// + public double MolesPerLiter => As(MolarityUnit.MolesPerLiter); + + /// + /// Get Molarity in NanomolesPerLiter. + /// + public double NanomolesPerLiter => As(MolarityUnit.NanomolesPerLiter); + + /// + /// Get Molarity in PicomolesPerLiter. + /// + public double PicomolesPerLiter => As(MolarityUnit.PicomolesPerLiter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromMicromolesPerLiter(QuantityValue? micromolesperliter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(MolarityUnit unit) { - return micromolesperliter.HasValue ? FromMicromolesPerLiter(micromolesperliter.Value) : default(Molarity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Molarity from nullable MillimolesPerLiter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromMillimolesPerLiter(QuantityValue? millimolesperliter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] IFormatProvider provider) { - return millimolesperliter.HasValue ? FromMillimolesPerLiter(millimolesperliter.Value) : default(Molarity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Molarity from nullable MolesPerCubicMeter. + /// Get Molarity from CentimolesPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromMolesPerCubicMeter(QuantityValue? molespercubicmeter) + /// If value is NaN or Infinity. + public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) { - return molespercubicmeter.HasValue ? FromMolesPerCubicMeter(molespercubicmeter.Value) : default(Molarity?); + double value = (double) centimolesperliter; + return new Molarity(value, MolarityUnit.CentimolesPerLiter); } - /// - /// Get nullable Molarity from nullable MolesPerLiter. + /// Get Molarity from DecimolesPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromMolesPerLiter(QuantityValue? molesperliter) + /// If value is NaN or Infinity. + public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) { - return molesperliter.HasValue ? FromMolesPerLiter(molesperliter.Value) : default(Molarity?); + double value = (double) decimolesperliter; + return new Molarity(value, MolarityUnit.DecimolesPerLiter); } - /// - /// Get nullable Molarity from nullable NanomolesPerLiter. + /// Get Molarity from MicromolesPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromNanomolesPerLiter(QuantityValue? nanomolesperliter) + /// If value is NaN or Infinity. + public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) { - return nanomolesperliter.HasValue ? FromNanomolesPerLiter(nanomolesperliter.Value) : default(Molarity?); + double value = (double) micromolesperliter; + return new Molarity(value, MolarityUnit.MicromolesPerLiter); + } + /// + /// Get Molarity from MillimolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) + { + double value = (double) millimolesperliter; + return new Molarity(value, MolarityUnit.MillimolesPerLiter); + } + /// + /// Get Molarity from MolesPerCubicMeter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) + { + double value = (double) molespercubicmeter; + return new Molarity(value, MolarityUnit.MolesPerCubicMeter); + } + /// + /// Get Molarity from MolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromMolesPerLiter(QuantityValue molesperliter) + { + double value = (double) molesperliter; + return new Molarity(value, MolarityUnit.MolesPerLiter); } - /// - /// Get nullable Molarity from nullable PicomolesPerLiter. + /// Get Molarity from NanomolesPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Molarity? FromPicomolesPerLiter(QuantityValue? picomolesperliter) + /// If value is NaN or Infinity. + public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) { - return picomolesperliter.HasValue ? FromPicomolesPerLiter(picomolesperliter.Value) : default(Molarity?); + double value = (double) nanomolesperliter; + return new Molarity(value, MolarityUnit.NanomolesPerLiter); + } + /// + /// Get Molarity from PicomolesPerLiter. + /// + /// If value is NaN or Infinity. + public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) + { + double value = (double) picomolesperliter; + return new Molarity(value, MolarityUnit.PicomolesPerLiter); } /// @@ -140,28 +298,156 @@ public partial struct Molarity : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Molarity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Molarity? From(QuantityValue? value, MolarityUnit fromUnit) + public static Molarity From(QuantityValue value, MolarityUnit fromUnit) { - return value.HasValue ? new Molarity((double)value.Value, fromUnit) : default(Molarity?); + return new Molarity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Molarity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Molarity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Molarity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static MolarityUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static MolarityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out MolarityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out MolarityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Molarity operator -(Molarity right) @@ -201,6 +487,8 @@ public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(Molarity left, Molarity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +509,230 @@ public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Molarity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Molarity left, Molarity right) + public static bool operator ==(Molarity left, Molarity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Molarity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Molarity left, Molarity right) + public static bool operator !=(Molarity left, Molarity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Molarity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Molarity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Molarity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - MolarityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMolesPerCubicMeter(x.MolesPerCubicMeter + y.MolesPerCubicMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Molarity result) + /// A hash code for the current Molarity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Molarity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Molarity to another Molarity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Molarity with the specified unit. + public Molarity ToUnit(MolarityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Molarity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return _value; + case MolarityUnit.MolesPerLiter: return _value/1e-3; + case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(MolarityUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == MolarityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; + case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; + case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(MolarityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs index 358cd8a59b..c837854442 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Permeability : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) + /// + public partial struct Permeability : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermeabilityUnit? _unit; + + static Permeability() + { + BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Permeability(double numericValue, PermeabilityUnit unit) + { + if(unit == PermeabilityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. + /// + public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; + + /// + /// Represents the largest possible value of Permeability + /// + public static Permeability MaxValue => new Permeability(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Permeability + /// + public static Permeability MinValue => new Permeability(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Permeability; + + /// + /// All units of measurement for the Permeability quantity. + /// + public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. + /// + public static Permeability Zero => new Permeability(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permeability.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permeability in HenriesPerMeter. + /// + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermeabilityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable Permeability from nullable HenriesPerMeter. + /// Get Permeability from HenriesPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Permeability? FromHenriesPerMeter(QuantityValue? henriespermeter) + /// If value is NaN or Infinity. + public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) { - return henriespermeter.HasValue ? FromHenriesPerMeter(henriespermeter.Value) : default(Permeability?); + double value = (double) henriespermeter; + return new Permeability(value, PermeabilityUnit.HenryPerMeter); } /// @@ -77,28 +200,156 @@ public partial struct Permeability : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Permeability unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Permeability? From(QuantityValue? value, PermeabilityUnit fromUnit) + public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) { - return value.HasValue ? new Permeability((double)value.Value, fromUnit) : default(Permeability?); + return new Permeability((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Permeability Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permeability result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permeability result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PermeabilityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermeabilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PermeabilityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Permeability operator -(Permeability right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(Permeability left, Permeability right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permeability, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Permeability left, Permeability right) + public static bool operator ==(Permeability left, Permeability right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permeability, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Permeability left, Permeability right) + public static bool operator !=(Permeability left, Permeability right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Permeability other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permeability Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PermeabilityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromHenriesPerMeter(x.HenriesPerMeter + y.HenriesPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permeability result) + /// A hash code for the current Permeability. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Permeability); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermeabilityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Permeability to another Permeability with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Permeability with the specified unit. + public Permeability ToUnit(PermeabilityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Permeability(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == PermeabilityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermeabilityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PermeabilityUnit.HenryPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs index c71f08473b..0135c92d4c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Permittivity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Permittivity + /// + public partial struct Permittivity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermittivityUnit? _unit; + + static Permittivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Permittivity(double numericValue, PermittivityUnit unit) + { + if(unit == PermittivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. + /// + public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; + + /// + /// Represents the largest possible value of Permittivity + /// + public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Permittivity + /// + public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Permittivity; + + /// + /// All units of measurement for the Permittivity quantity. + /// + public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. + /// + public static Permittivity Zero => new Permittivity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Permittivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Permittivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Permittivity in FaradsPerMeter. + /// + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PermittivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable Permittivity from nullable FaradsPerMeter. + /// Get Permittivity from FaradsPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Permittivity? FromFaradsPerMeter(QuantityValue? faradspermeter) + /// If value is NaN or Infinity. + public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) { - return faradspermeter.HasValue ? FromFaradsPerMeter(faradspermeter.Value) : default(Permittivity?); + double value = (double) faradspermeter; + return new Permittivity(value, PermittivityUnit.FaradPerMeter); } /// @@ -77,28 +200,156 @@ public partial struct Permittivity : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Permittivity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Permittivity? From(QuantityValue? value, PermittivityUnit fromUnit) + public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) { - return value.HasValue ? new Permittivity((double)value.Value, fromUnit) : default(Permittivity?); + return new Permittivity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Permittivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Permittivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permittivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PermittivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PermittivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PermittivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PermittivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Permittivity operator -(Permittivity right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(Permittivity left, Permittivity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permittivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Permittivity left, Permittivity right) + public static bool operator ==(Permittivity left, Permittivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Permittivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Permittivity left, Permittivity right) + public static bool operator !=(Permittivity left, Permittivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(Permittivity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permittivity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PermittivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromFaradsPerMeter(x.FaradsPerMeter + y.FaradsPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permittivity result) + /// A hash code for the current Permittivity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Permittivity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermittivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Permittivity to another Permittivity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Permittivity with the specified unit. + public Permittivity ToUnit(PermittivityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Permittivity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermittivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == PermittivityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermittivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PermittivityUnit.FaradPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PermittivityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs index 1f5c656fcc..5af1aba2d9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,195 +49,412 @@ namespace UnitsNet /// /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Power : IComparable, IComparable + public partial struct Power : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public decimal Value => _value; - - #region Nullable From Methods + private readonly decimal _value; /// - /// Get nullable Power from nullable BoilerHorsepower. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromBoilerHorsepower(QuantityValue? boilerhorsepower) + private readonly PowerUnit? _unit; + + static Power() { - return boilerhorsepower.HasValue ? FromBoilerHorsepower(boilerhorsepower.Value) : default(Power?); + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); } /// - /// Get nullable Power from nullable BritishThermalUnitsPerHour. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromBritishThermalUnitsPerHour(QuantityValue? britishthermalunitsperhour) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Power(decimal numericValue, PowerUnit unit) { - return britishthermalunitsperhour.HasValue ? FromBritishThermalUnitsPerHour(britishthermalunitsperhour.Value) : default(Power?); + if(unit == PowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = numericValue; + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Power, which is Watt. All conversions go via this value. + /// + public static PowerUnit BaseUnit => PowerUnit.Watt; + + /// + /// Represents the largest possible value of Power + /// + public static Power MaxValue => new Power(decimal.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Power + /// + public static Power MinValue => new Power(decimal.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Power; + + /// + /// All units of measurement for the Power quantity. + /// + public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// + public static Power Zero => new Power(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public decimal Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Power.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Power.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Power in BoilerHorsepower. + /// + public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + + /// + /// Get Power in BritishThermalUnitsPerHour. + /// + public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + + /// + /// Get Power in Decawatts. + /// + public double Decawatts => As(PowerUnit.Decawatt); + + /// + /// Get Power in Deciwatts. + /// + public double Deciwatts => As(PowerUnit.Deciwatt); + + /// + /// Get Power in ElectricalHorsepower. + /// + public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + + /// + /// Get Power in Femtowatts. + /// + public double Femtowatts => As(PowerUnit.Femtowatt); + + /// + /// Get Power in Gigawatts. + /// + public double Gigawatts => As(PowerUnit.Gigawatt); + + /// + /// Get Power in HydraulicHorsepower. + /// + public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + + /// + /// Get Power in KilobritishThermalUnitsPerHour. + /// + public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + + /// + /// Get Power in Kilowatts. + /// + public double Kilowatts => As(PowerUnit.Kilowatt); + + /// + /// Get Power in MechanicalHorsepower. + /// + public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + + /// + /// Get Power in Megawatts. + /// + public double Megawatts => As(PowerUnit.Megawatt); + + /// + /// Get Power in MetricHorsepower. + /// + public double MetricHorsepower => As(PowerUnit.MetricHorsepower); + + /// + /// Get Power in Microwatts. + /// + public double Microwatts => As(PowerUnit.Microwatt); + + /// + /// Get Power in Milliwatts. + /// + public double Milliwatts => As(PowerUnit.Milliwatt); + + /// + /// Get Power in Nanowatts. + /// + public double Nanowatts => As(PowerUnit.Nanowatt); + + /// + /// Get Power in Petawatts. + /// + public double Petawatts => As(PowerUnit.Petawatt); + + /// + /// Get Power in Picowatts. + /// + public double Picowatts => As(PowerUnit.Picowatt); + + /// + /// Get Power in Terawatts. + /// + public double Terawatts => As(PowerUnit.Terawatt); + + /// + /// Get Power in Watts. + /// + public double Watts => As(PowerUnit.Watt); + + #endregion + + #region Static Methods + /// - /// Get nullable Power from nullable Decawatts. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromDecawatts(QuantityValue? decawatts) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerUnit unit) { - return decawatts.HasValue ? FromDecawatts(decawatts.Value) : default(Power?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Power from nullable Deciwatts. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromDeciwatts(QuantityValue? deciwatts) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PowerUnit unit, [CanBeNull] IFormatProvider provider) { - return deciwatts.HasValue ? FromDeciwatts(deciwatts.Value) : default(Power?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Power from nullable ElectricalHorsepower. + /// Get Power from BoilerHorsepower. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromElectricalHorsepower(QuantityValue? electricalhorsepower) + /// If value is NaN or Infinity. + public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) { - return electricalhorsepower.HasValue ? FromElectricalHorsepower(electricalhorsepower.Value) : default(Power?); + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); } - /// - /// Get nullable Power from nullable Femtowatts. + /// Get Power from BritishThermalUnitsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromFemtowatts(QuantityValue? femtowatts) + /// If value is NaN or Infinity. + public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) { - return femtowatts.HasValue ? FromFemtowatts(femtowatts.Value) : default(Power?); + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); } - /// - /// Get nullable Power from nullable Gigawatts. + /// Get Power from Decawatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromGigawatts(QuantityValue? gigawatts) + /// If value is NaN or Infinity. + public static Power FromDecawatts(QuantityValue decawatts) { - return gigawatts.HasValue ? FromGigawatts(gigawatts.Value) : default(Power?); + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); } - /// - /// Get nullable Power from nullable HydraulicHorsepower. + /// Get Power from Deciwatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromHydraulicHorsepower(QuantityValue? hydraulichorsepower) + /// If value is NaN or Infinity. + public static Power FromDeciwatts(QuantityValue deciwatts) { - return hydraulichorsepower.HasValue ? FromHydraulicHorsepower(hydraulichorsepower.Value) : default(Power?); + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); } - /// - /// Get nullable Power from nullable KilobritishThermalUnitsPerHour. + /// Get Power from ElectricalHorsepower. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromKilobritishThermalUnitsPerHour(QuantityValue? kilobritishthermalunitsperhour) + /// If value is NaN or Infinity. + public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) { - return kilobritishthermalunitsperhour.HasValue ? FromKilobritishThermalUnitsPerHour(kilobritishthermalunitsperhour.Value) : default(Power?); + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); } - /// - /// Get nullable Power from nullable Kilowatts. + /// Get Power from Femtowatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromKilowatts(QuantityValue? kilowatts) + /// If value is NaN or Infinity. + public static Power FromFemtowatts(QuantityValue femtowatts) { - return kilowatts.HasValue ? FromKilowatts(kilowatts.Value) : default(Power?); + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); } - /// - /// Get nullable Power from nullable MechanicalHorsepower. + /// Get Power from Gigawatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromMechanicalHorsepower(QuantityValue? mechanicalhorsepower) + /// If value is NaN or Infinity. + public static Power FromGigawatts(QuantityValue gigawatts) { - return mechanicalhorsepower.HasValue ? FromMechanicalHorsepower(mechanicalhorsepower.Value) : default(Power?); + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); } - /// - /// Get nullable Power from nullable Megawatts. + /// Get Power from HydraulicHorsepower. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromMegawatts(QuantityValue? megawatts) + /// If value is NaN or Infinity. + public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) { - return megawatts.HasValue ? FromMegawatts(megawatts.Value) : default(Power?); + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); } - /// - /// Get nullable Power from nullable MetricHorsepower. + /// Get Power from KilobritishThermalUnitsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromMetricHorsepower(QuantityValue? metrichorsepower) + /// If value is NaN or Infinity. + public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) { - return metrichorsepower.HasValue ? FromMetricHorsepower(metrichorsepower.Value) : default(Power?); + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); } - /// - /// Get nullable Power from nullable Microwatts. + /// Get Power from Kilowatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromMicrowatts(QuantityValue? microwatts) + /// If value is NaN or Infinity. + public static Power FromKilowatts(QuantityValue kilowatts) { - return microwatts.HasValue ? FromMicrowatts(microwatts.Value) : default(Power?); + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); } - /// - /// Get nullable Power from nullable Milliwatts. + /// Get Power from MechanicalHorsepower. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromMilliwatts(QuantityValue? milliwatts) + /// If value is NaN or Infinity. + public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) { - return milliwatts.HasValue ? FromMilliwatts(milliwatts.Value) : default(Power?); + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); } - /// - /// Get nullable Power from nullable Nanowatts. + /// Get Power from Megawatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromNanowatts(QuantityValue? nanowatts) + /// If value is NaN or Infinity. + public static Power FromMegawatts(QuantityValue megawatts) { - return nanowatts.HasValue ? FromNanowatts(nanowatts.Value) : default(Power?); + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); } - /// - /// Get nullable Power from nullable Petawatts. + /// Get Power from MetricHorsepower. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromPetawatts(QuantityValue? petawatts) + /// If value is NaN or Infinity. + public static Power FromMetricHorsepower(QuantityValue metrichorsepower) { - return petawatts.HasValue ? FromPetawatts(petawatts.Value) : default(Power?); + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); } - /// - /// Get nullable Power from nullable Picowatts. + /// Get Power from Microwatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromPicowatts(QuantityValue? picowatts) + /// If value is NaN or Infinity. + public static Power FromMicrowatts(QuantityValue microwatts) { - return picowatts.HasValue ? FromPicowatts(picowatts.Value) : default(Power?); + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); } - /// - /// Get nullable Power from nullable Terawatts. + /// Get Power from Milliwatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromTerawatts(QuantityValue? terawatts) + /// If value is NaN or Infinity. + public static Power FromMilliwatts(QuantityValue milliwatts) { - return terawatts.HasValue ? FromTerawatts(terawatts.Value) : default(Power?); + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); + } + /// + /// Get Power from Nanowatts. + /// + /// If value is NaN or Infinity. + public static Power FromNanowatts(QuantityValue nanowatts) + { + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); + } + /// + /// Get Power from Petawatts. + /// + /// If value is NaN or Infinity. + public static Power FromPetawatts(QuantityValue petawatts) + { + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); + } + /// + /// Get Power from Picowatts. + /// + /// If value is NaN or Infinity. + public static Power FromPicowatts(QuantityValue picowatts) + { + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); } - /// - /// Get nullable Power from nullable Watts. + /// Get Power from Terawatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Power? FromWatts(QuantityValue? watts) + /// If value is NaN or Infinity. + public static Power FromTerawatts(QuantityValue terawatts) { - return watts.HasValue ? FromWatts(watts.Value) : default(Power?); + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); + } + /// + /// Get Power from Watts. + /// + /// If value is NaN or Infinity. + public static Power FromWatts(QuantityValue watts) + { + decimal value = (decimal) watts; + return new Power(value, PowerUnit.Watt); } /// @@ -248,28 +463,156 @@ public partial struct Power : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Power unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Power? From(QuantityValue? value, PowerUnit fromUnit) + public static Power From(QuantityValue value, PowerUnit fromUnit) { - return value.HasValue ? new Power((decimal)value.Value, fromUnit) : default(Power?); + return new Power((decimal)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static Power Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Power Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Power result) { - provider = provider ?? UnitSystem.DefaultCulture; + return TryParse(str, null, out result); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Power result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static Power operator -(Power right) @@ -309,6 +652,8 @@ public static string GetAbbreviation(PowerUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Power left, Power right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -329,178 +674,254 @@ public static string GetAbbreviation(PowerUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - public static bool operator ==(Power left, Power right) + public static bool operator ==(Power left, Power right) + { + return left.Equals(right); + } + + public static bool operator !=(Power left, Power right) + { + return !(left == right); + } + + 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 + public int CompareTo(Power other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - public static bool operator !=(Power left, Power right) + public override bool Equals(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + if(obj is null || !(obj is Power objPower)) + return false; + + return Equals(objPower); } - #region Parsing + public bool Equals(Power other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Power Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Power other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWatts(x.Watts + y.Watts)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Power result) + /// A hash code for the current Power. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Power); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Power to another Power with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Power with the specified unit. + public Power ToUnit(PowerUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Power(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private decimal AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case PowerUnit.BoilerHorsepower: return _value*9812.5m; + case PowerUnit.BritishThermalUnitPerHour: return _value*0.293071m; + case PowerUnit.Decawatt: return (_value) * 1e1m; + case PowerUnit.Deciwatt: return (_value) * 1e-1m; + case PowerUnit.ElectricalHorsepower: return _value*746m; + case PowerUnit.Femtowatt: return (_value) * 1e-15m; + case PowerUnit.Gigawatt: return (_value) * 1e9m; + case PowerUnit.HydraulicHorsepower: return _value*745.69988145m; + case PowerUnit.KilobritishThermalUnitPerHour: return (_value*0.293071m) * 1e3m; + case PowerUnit.Kilowatt: return (_value) * 1e3m; + case PowerUnit.MechanicalHorsepower: return _value*745.69m; + case PowerUnit.Megawatt: return (_value) * 1e6m; + case PowerUnit.MetricHorsepower: return _value*735.49875m; + case PowerUnit.Microwatt: return (_value) * 1e-6m; + case PowerUnit.Milliwatt: return (_value) * 1e-3m; + case PowerUnit.Nanowatt: return (_value) * 1e-9m; + case PowerUnit.Petawatt: return (_value) * 1e15m; + case PowerUnit.Picowatt: return (_value) * 1e-12m; + case PowerUnit.Terawatt: return (_value) * 1e12m; + case PowerUnit.Watt: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private decimal AsBaseNumericType(PowerUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - if (unit == PowerUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PowerUnit.BoilerHorsepower: return baseUnitValue/9812.5m; + case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue/0.293071m; + case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; + case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; + case PowerUnit.ElectricalHorsepower: return baseUnitValue/746m; + case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; + case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; + case PowerUnit.HydraulicHorsepower: return baseUnitValue/745.69988145m; + case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue/0.293071m) / 1e3m; + case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; + case PowerUnit.MechanicalHorsepower: return baseUnitValue/745.69m; + case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; + case PowerUnit.MetricHorsepower: return baseUnitValue/735.49875m; + case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; + case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; + case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; + case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; + case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; + case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; + case PowerUnit.Watt: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PowerUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs index 08efb64ad4..0561b93c66 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,411 +49,748 @@ namespace UnitsNet /// /// The amount of power in a volume. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct PowerDensity : IComparable, IComparable + public partial struct PowerDensity : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable PowerDensity from nullable DecawattsPerCubicFoot. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDecawattsPerCubicFoot(QuantityValue? decawattspercubicfoot) + private readonly PowerDensityUnit? _unit; + + static PowerDensity() { - return decawattspercubicfoot.HasValue ? FromDecawattsPerCubicFoot(decawattspercubicfoot.Value) : default(PowerDensity?); + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); } /// - /// Get nullable PowerDensity from nullable DecawattsPerCubicInch. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDecawattsPerCubicInch(QuantityValue? decawattspercubicinch) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public PowerDensity(double numericValue, PowerDensityUnit unit) { - return decawattspercubicinch.HasValue ? FromDecawattsPerCubicInch(decawattspercubicinch.Value) : default(PowerDensity?); + if(unit == PowerDensityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. + /// + public static PowerDensityUnit BaseUnit => PowerDensityUnit.WattPerCubicMeter; + + /// + /// Represents the largest possible value of PowerDensity + /// + public static PowerDensity MaxValue => new PowerDensity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of PowerDensity + /// + public static PowerDensity MinValue => new PowerDensity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PowerDensity; + + /// + /// All units of measurement for the PowerDensity quantity. + /// + public static PowerDensityUnit[] Units { get; } = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. + /// + public static PowerDensity Zero => new PowerDensity(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerDensity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PowerDensity in DecawattsPerCubicFoot. + /// + public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); + + /// + /// Get PowerDensity in DecawattsPerCubicInch. + /// + public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); + + /// + /// Get PowerDensity in DecawattsPerCubicMeter. + /// + public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); + + /// + /// Get PowerDensity in DecawattsPerLiter. + /// + public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); + + /// + /// Get PowerDensity in DeciwattsPerCubicFoot. + /// + public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); + + /// + /// Get PowerDensity in DeciwattsPerCubicInch. + /// + public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); + + /// + /// Get PowerDensity in DeciwattsPerCubicMeter. + /// + public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); + + /// + /// Get PowerDensity in DeciwattsPerLiter. + /// + public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); + + /// + /// Get PowerDensity in GigawattsPerCubicFoot. + /// + public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); + + /// + /// Get PowerDensity in GigawattsPerCubicInch. + /// + public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); + + /// + /// Get PowerDensity in GigawattsPerCubicMeter. + /// + public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); + + /// + /// Get PowerDensity in GigawattsPerLiter. + /// + public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); + + /// + /// Get PowerDensity in KilowattsPerCubicFoot. + /// + public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); + + /// + /// Get PowerDensity in KilowattsPerCubicInch. + /// + public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); + + /// + /// Get PowerDensity in KilowattsPerCubicMeter. + /// + public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); + + /// + /// Get PowerDensity in KilowattsPerLiter. + /// + public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); + + /// + /// Get PowerDensity in MegawattsPerCubicFoot. + /// + public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); + + /// + /// Get PowerDensity in MegawattsPerCubicInch. + /// + public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); + + /// + /// Get PowerDensity in MegawattsPerCubicMeter. + /// + public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); + + /// + /// Get PowerDensity in MegawattsPerLiter. + /// + public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); + + /// + /// Get PowerDensity in MicrowattsPerCubicFoot. + /// + public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); + + /// + /// Get PowerDensity in MicrowattsPerCubicInch. + /// + public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); + + /// + /// Get PowerDensity in MicrowattsPerCubicMeter. + /// + public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); + + /// + /// Get PowerDensity in MicrowattsPerLiter. + /// + public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); + + /// + /// Get PowerDensity in MilliwattsPerCubicFoot. + /// + public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); + + /// + /// Get PowerDensity in MilliwattsPerCubicInch. + /// + public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); + + /// + /// Get PowerDensity in MilliwattsPerCubicMeter. + /// + public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); + + /// + /// Get PowerDensity in MilliwattsPerLiter. + /// + public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); + + /// + /// Get PowerDensity in NanowattsPerCubicFoot. + /// + public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); + + /// + /// Get PowerDensity in NanowattsPerCubicInch. + /// + public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); + + /// + /// Get PowerDensity in NanowattsPerCubicMeter. + /// + public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); + + /// + /// Get PowerDensity in NanowattsPerLiter. + /// + public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); + + /// + /// Get PowerDensity in PicowattsPerCubicFoot. + /// + public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); + + /// + /// Get PowerDensity in PicowattsPerCubicInch. + /// + public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); + + /// + /// Get PowerDensity in PicowattsPerCubicMeter. + /// + public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); + + /// + /// Get PowerDensity in PicowattsPerLiter. + /// + public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); + + /// + /// Get PowerDensity in TerawattsPerCubicFoot. + /// + public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); + + /// + /// Get PowerDensity in TerawattsPerCubicInch. + /// + public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); + + /// + /// Get PowerDensity in TerawattsPerCubicMeter. + /// + public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); + + /// + /// Get PowerDensity in TerawattsPerLiter. + /// + public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); + /// - /// Get nullable PowerDensity from nullable DecawattsPerCubicMeter. + /// Get PowerDensity in WattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDecawattsPerCubicMeter(QuantityValue? decawattspercubicmeter) + public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); + + /// + /// Get PowerDensity in WattsPerCubicInch. + /// + public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); + + /// + /// Get PowerDensity in WattsPerCubicMeter. + /// + public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); + + /// + /// Get PowerDensity in WattsPerLiter. + /// + public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerDensityUnit unit) { - return decawattspercubicmeter.HasValue ? FromDecawattsPerCubicMeter(decawattspercubicmeter.Value) : default(PowerDensity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable PowerDensity from nullable DecawattsPerLiter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDecawattsPerLiter(QuantityValue? decawattsperliter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider) { - return decawattsperliter.HasValue ? FromDecawattsPerLiter(decawattsperliter.Value) : default(PowerDensity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable PowerDensity from nullable DeciwattsPerCubicFoot. + /// Get PowerDensity from DecawattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDeciwattsPerCubicFoot(QuantityValue? deciwattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) { - return deciwattspercubicfoot.HasValue ? FromDeciwattsPerCubicFoot(deciwattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) decawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable DeciwattsPerCubicInch. + /// Get PowerDensity from DecawattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDeciwattsPerCubicInch(QuantityValue? deciwattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) { - return deciwattspercubicinch.HasValue ? FromDeciwattsPerCubicInch(deciwattspercubicinch.Value) : default(PowerDensity?); + double value = (double) decawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable DeciwattsPerCubicMeter. + /// Get PowerDensity from DecawattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDeciwattsPerCubicMeter(QuantityValue? deciwattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) { - return deciwattspercubicmeter.HasValue ? FromDeciwattsPerCubicMeter(deciwattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) decawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable DeciwattsPerLiter. + /// Get PowerDensity from DecawattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromDeciwattsPerLiter(QuantityValue? deciwattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) { - return deciwattsperliter.HasValue ? FromDeciwattsPerLiter(deciwattsperliter.Value) : default(PowerDensity?); + double value = (double) decawattsperliter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); } - /// - /// Get nullable PowerDensity from nullable GigawattsPerCubicFoot. + /// Get PowerDensity from DeciwattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromGigawattsPerCubicFoot(QuantityValue? gigawattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) { - return gigawattspercubicfoot.HasValue ? FromGigawattsPerCubicFoot(gigawattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) deciwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable GigawattsPerCubicInch. + /// Get PowerDensity from DeciwattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromGigawattsPerCubicInch(QuantityValue? gigawattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) { - return gigawattspercubicinch.HasValue ? FromGigawattsPerCubicInch(gigawattspercubicinch.Value) : default(PowerDensity?); + double value = (double) deciwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable GigawattsPerCubicMeter. + /// Get PowerDensity from DeciwattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromGigawattsPerCubicMeter(QuantityValue? gigawattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) { - return gigawattspercubicmeter.HasValue ? FromGigawattsPerCubicMeter(gigawattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) deciwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable GigawattsPerLiter. + /// Get PowerDensity from DeciwattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromGigawattsPerLiter(QuantityValue? gigawattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) { - return gigawattsperliter.HasValue ? FromGigawattsPerLiter(gigawattsperliter.Value) : default(PowerDensity?); + double value = (double) deciwattsperliter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); } - /// - /// Get nullable PowerDensity from nullable KilowattsPerCubicFoot. + /// Get PowerDensity from GigawattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromKilowattsPerCubicFoot(QuantityValue? kilowattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) { - return kilowattspercubicfoot.HasValue ? FromKilowattsPerCubicFoot(kilowattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) gigawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable KilowattsPerCubicInch. + /// Get PowerDensity from GigawattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromKilowattsPerCubicInch(QuantityValue? kilowattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) { - return kilowattspercubicinch.HasValue ? FromKilowattsPerCubicInch(kilowattspercubicinch.Value) : default(PowerDensity?); + double value = (double) gigawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable KilowattsPerCubicMeter. + /// Get PowerDensity from GigawattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromKilowattsPerCubicMeter(QuantityValue? kilowattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) { - return kilowattspercubicmeter.HasValue ? FromKilowattsPerCubicMeter(kilowattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) gigawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable KilowattsPerLiter. + /// Get PowerDensity from GigawattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromKilowattsPerLiter(QuantityValue? kilowattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) { - return kilowattsperliter.HasValue ? FromKilowattsPerLiter(kilowattsperliter.Value) : default(PowerDensity?); + double value = (double) gigawattsperliter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); } - /// - /// Get nullable PowerDensity from nullable MegawattsPerCubicFoot. + /// Get PowerDensity from KilowattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMegawattsPerCubicFoot(QuantityValue? megawattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) { - return megawattspercubicfoot.HasValue ? FromMegawattsPerCubicFoot(megawattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) kilowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable MegawattsPerCubicInch. + /// Get PowerDensity from KilowattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMegawattsPerCubicInch(QuantityValue? megawattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) { - return megawattspercubicinch.HasValue ? FromMegawattsPerCubicInch(megawattspercubicinch.Value) : default(PowerDensity?); + double value = (double) kilowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable MegawattsPerCubicMeter. + /// Get PowerDensity from KilowattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMegawattsPerCubicMeter(QuantityValue? megawattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) { - return megawattspercubicmeter.HasValue ? FromMegawattsPerCubicMeter(megawattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) kilowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable MegawattsPerLiter. + /// Get PowerDensity from KilowattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMegawattsPerLiter(QuantityValue? megawattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) { - return megawattsperliter.HasValue ? FromMegawattsPerLiter(megawattsperliter.Value) : default(PowerDensity?); + double value = (double) kilowattsperliter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); } - /// - /// Get nullable PowerDensity from nullable MicrowattsPerCubicFoot. + /// Get PowerDensity from MegawattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMicrowattsPerCubicFoot(QuantityValue? microwattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) { - return microwattspercubicfoot.HasValue ? FromMicrowattsPerCubicFoot(microwattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) megawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable MicrowattsPerCubicInch. + /// Get PowerDensity from MegawattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMicrowattsPerCubicInch(QuantityValue? microwattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) { - return microwattspercubicinch.HasValue ? FromMicrowattsPerCubicInch(microwattspercubicinch.Value) : default(PowerDensity?); + double value = (double) megawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable MicrowattsPerCubicMeter. + /// Get PowerDensity from MegawattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMicrowattsPerCubicMeter(QuantityValue? microwattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) { - return microwattspercubicmeter.HasValue ? FromMicrowattsPerCubicMeter(microwattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) megawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable MicrowattsPerLiter. + /// Get PowerDensity from MegawattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMicrowattsPerLiter(QuantityValue? microwattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) { - return microwattsperliter.HasValue ? FromMicrowattsPerLiter(microwattsperliter.Value) : default(PowerDensity?); + double value = (double) megawattsperliter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); } - /// - /// Get nullable PowerDensity from nullable MilliwattsPerCubicFoot. + /// Get PowerDensity from MicrowattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMilliwattsPerCubicFoot(QuantityValue? milliwattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) { - return milliwattspercubicfoot.HasValue ? FromMilliwattsPerCubicFoot(milliwattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) microwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable MilliwattsPerCubicInch. + /// Get PowerDensity from MicrowattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMilliwattsPerCubicInch(QuantityValue? milliwattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) { - return milliwattspercubicinch.HasValue ? FromMilliwattsPerCubicInch(milliwattspercubicinch.Value) : default(PowerDensity?); + double value = (double) microwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable MilliwattsPerCubicMeter. + /// Get PowerDensity from MicrowattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMilliwattsPerCubicMeter(QuantityValue? milliwattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) { - return milliwattspercubicmeter.HasValue ? FromMilliwattsPerCubicMeter(milliwattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) microwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable MilliwattsPerLiter. + /// Get PowerDensity from MicrowattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromMilliwattsPerLiter(QuantityValue? milliwattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) { - return milliwattsperliter.HasValue ? FromMilliwattsPerLiter(milliwattsperliter.Value) : default(PowerDensity?); + double value = (double) microwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); } - /// - /// Get nullable PowerDensity from nullable NanowattsPerCubicFoot. + /// Get PowerDensity from MilliwattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromNanowattsPerCubicFoot(QuantityValue? nanowattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) { - return nanowattspercubicfoot.HasValue ? FromNanowattsPerCubicFoot(nanowattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) milliwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable NanowattsPerCubicInch. + /// Get PowerDensity from MilliwattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromNanowattsPerCubicInch(QuantityValue? nanowattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) { - return nanowattspercubicinch.HasValue ? FromNanowattsPerCubicInch(nanowattspercubicinch.Value) : default(PowerDensity?); + double value = (double) milliwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable NanowattsPerCubicMeter. + /// Get PowerDensity from MilliwattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromNanowattsPerCubicMeter(QuantityValue? nanowattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) { - return nanowattspercubicmeter.HasValue ? FromNanowattsPerCubicMeter(nanowattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) milliwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable NanowattsPerLiter. + /// Get PowerDensity from MilliwattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromNanowattsPerLiter(QuantityValue? nanowattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) { - return nanowattsperliter.HasValue ? FromNanowattsPerLiter(nanowattsperliter.Value) : default(PowerDensity?); + double value = (double) milliwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); } - /// - /// Get nullable PowerDensity from nullable PicowattsPerCubicFoot. + /// Get PowerDensity from NanowattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromPicowattsPerCubicFoot(QuantityValue? picowattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) { - return picowattspercubicfoot.HasValue ? FromPicowattsPerCubicFoot(picowattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) nanowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable PicowattsPerCubicInch. + /// Get PowerDensity from NanowattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromPicowattsPerCubicInch(QuantityValue? picowattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) { - return picowattspercubicinch.HasValue ? FromPicowattsPerCubicInch(picowattspercubicinch.Value) : default(PowerDensity?); + double value = (double) nanowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable PicowattsPerCubicMeter. + /// Get PowerDensity from NanowattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromPicowattsPerCubicMeter(QuantityValue? picowattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) { - return picowattspercubicmeter.HasValue ? FromPicowattsPerCubicMeter(picowattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) nanowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable PicowattsPerLiter. + /// Get PowerDensity from NanowattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromPicowattsPerLiter(QuantityValue? picowattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) { - return picowattsperliter.HasValue ? FromPicowattsPerLiter(picowattsperliter.Value) : default(PowerDensity?); + double value = (double) nanowattsperliter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); } - /// - /// Get nullable PowerDensity from nullable TerawattsPerCubicFoot. + /// Get PowerDensity from PicowattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromTerawattsPerCubicFoot(QuantityValue? terawattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) { - return terawattspercubicfoot.HasValue ? FromTerawattsPerCubicFoot(terawattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) picowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable TerawattsPerCubicInch. + /// Get PowerDensity from PicowattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromTerawattsPerCubicInch(QuantityValue? terawattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) { - return terawattspercubicinch.HasValue ? FromTerawattsPerCubicInch(terawattspercubicinch.Value) : default(PowerDensity?); + double value = (double) picowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable TerawattsPerCubicMeter. + /// Get PowerDensity from PicowattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromTerawattsPerCubicMeter(QuantityValue? terawattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) { - return terawattspercubicmeter.HasValue ? FromTerawattsPerCubicMeter(terawattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) picowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); } - /// - /// Get nullable PowerDensity from nullable TerawattsPerLiter. + /// Get PowerDensity from PicowattsPerLiter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromTerawattsPerLiter(QuantityValue? terawattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) { - return terawattsperliter.HasValue ? FromTerawattsPerLiter(terawattsperliter.Value) : default(PowerDensity?); + double value = (double) picowattsperliter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); } - /// - /// Get nullable PowerDensity from nullable WattsPerCubicFoot. + /// Get PowerDensity from TerawattsPerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromWattsPerCubicFoot(QuantityValue? wattspercubicfoot) + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) { - return wattspercubicfoot.HasValue ? FromWattsPerCubicFoot(wattspercubicfoot.Value) : default(PowerDensity?); + double value = (double) terawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); } - /// - /// Get nullable PowerDensity from nullable WattsPerCubicInch. + /// Get PowerDensity from TerawattsPerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromWattsPerCubicInch(QuantityValue? wattspercubicinch) + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) { - return wattspercubicinch.HasValue ? FromWattsPerCubicInch(wattspercubicinch.Value) : default(PowerDensity?); + double value = (double) terawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable WattsPerCubicMeter. + /// Get PowerDensity from TerawattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromWattsPerCubicMeter(QuantityValue? wattspercubicmeter) + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) { - return wattspercubicmeter.HasValue ? FromWattsPerCubicMeter(wattspercubicmeter.Value) : default(PowerDensity?); + double value = (double) terawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); + } + /// + /// Get PowerDensity from TerawattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) + { + double value = (double) terawattsperliter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); + } + /// + /// Get PowerDensity from WattsPerCubicFoot. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) + { + double value = (double) wattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); + } + /// + /// Get PowerDensity from WattsPerCubicInch. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) + { + double value = (double) wattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); } - /// - /// Get nullable PowerDensity from nullable WattsPerLiter. + /// Get PowerDensity from WattsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerDensity? FromWattsPerLiter(QuantityValue? wattsperliter) + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) { - return wattsperliter.HasValue ? FromWattsPerLiter(wattsperliter.Value) : default(PowerDensity?); + double value = (double) wattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); + } + /// + /// Get PowerDensity from WattsPerLiter. + /// + /// If value is NaN or Infinity. + public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) + { + double value = (double) wattsperliter; + return new PowerDensity(value, PowerDensityUnit.WattPerLiter); } /// @@ -464,28 +799,156 @@ public partial struct PowerDensity : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// PowerDensity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerDensity? From(QuantityValue? value, PowerDensityUnit fromUnit) + public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) { - return value.HasValue ? new PowerDensity((double)value.Value, fromUnit) : default(PowerDensity?); + return new PowerDensity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static PowerDensity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerDensity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerDensity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PowerDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PowerDensityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PowerDensityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static PowerDensity operator -(PowerDensity right) @@ -525,6 +988,8 @@ public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] IFormatP #endregion + #region Equality / IComparable + public static bool operator <=(PowerDensity left, PowerDensity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -545,180 +1010,302 @@ public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] IFormatP return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(PowerDensity left, PowerDensity right) + public static bool operator ==(PowerDensity left, PowerDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerDensity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(PowerDensity left, PowerDensity right) + public static bool operator !=(PowerDensity left, PowerDensity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(PowerDensity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerDensity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerDensityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerCubicMeter(x.WattsPerCubicMeter + y.WattsPerCubicMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerDensity result) + /// A hash code for the current PowerDensity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(PowerDensity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerDensityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this PowerDensity to another PowerDensity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A PowerDensity with the specified unit. + public PowerDensity ToUnit(PowerDensityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new PowerDensity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerDensityUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(PowerDensityUnit unit) + { + if(Unit == unit) + return _value; - if (unit == PowerDensityUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerDensityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerDensityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs index c5c5c6576b..3173544500 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// The strength of a signal expressed in decibels (dB) relative to one watt. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct PowerRatio : IComparable, IComparable + public partial struct PowerRatio : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerRatioUnit? _unit; + + static PowerRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public PowerRatio(double numericValue, PowerRatioUnit unit) + { + if(unit == PowerRatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. + /// + public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; + + /// + /// Represents the largest possible value of PowerRatio + /// + public static PowerRatio MaxValue => new PowerRatio(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of PowerRatio + /// + public static PowerRatio MinValue => new PowerRatio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PowerRatio; + + /// + /// All units of measurement for the PowerRatio quantity. + /// + public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. + /// + public static PowerRatio Zero => new PowerRatio(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PowerRatio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable PowerRatio from nullable DecibelMilliwatts. + /// Get PowerRatio in DecibelMilliwatts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerRatio? FromDecibelMilliwatts(QuantityValue? decibelmilliwatts) + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + + /// + /// Get PowerRatio in DecibelWatts. + /// + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PowerRatioUnit unit) { - return decibelmilliwatts.HasValue ? FromDecibelMilliwatts(decibelmilliwatts.Value) : default(PowerRatio?); + return GetAbbreviation(unit, null); } /// - /// Get nullable PowerRatio from nullable DecibelWatts. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PowerRatio? FromDecibelWatts(QuantityValue? decibelwatts) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider) { - return decibelwatts.HasValue ? FromDecibelWatts(decibelwatts.Value) : default(PowerRatio?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get PowerRatio from DecibelMilliwatts. + /// + /// If value is NaN or Infinity. + public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) + { + double value = (double) decibelmilliwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); + } + /// + /// Get PowerRatio from DecibelWatts. + /// + /// If value is NaN or Infinity. + public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) + { + double value = (double) decibelwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelWatt); } /// @@ -86,28 +211,156 @@ public partial struct PowerRatio : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// PowerRatio unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PowerRatio? From(QuantityValue? value, PowerRatioUnit fromUnit) + public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) { - return value.HasValue ? new PowerRatio((double)value.Value, fromUnit) : default(PowerRatio?); + return new PowerRatio((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static PowerRatio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PowerRatio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerRatio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PowerRatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PowerRatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PowerRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PowerRatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Logarithmic Arithmetic Operators public static PowerRatio operator -(PowerRatio right) @@ -155,6 +408,8 @@ public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] IFormatPro #endregion + #region Equality / IComparable + public static bool operator <=(PowerRatio left, PowerRatio right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -175,180 +430,218 @@ public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] IFormatPro return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(PowerRatio left, PowerRatio right) + public static bool operator ==(PowerRatio left, PowerRatio right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PowerRatio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(PowerRatio left, PowerRatio right) + public static bool operator !=(PowerRatio left, PowerRatio right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(PowerRatio other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerRatio Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(PowerRatio other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PowerRatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecibelWatts(x.DecibelWatts + y.DecibelWatts)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PowerRatio result) + /// A hash code for the current PowerRatio. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(PowerRatio); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerRatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this PowerRatio to another PowerRatio with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A PowerRatio with the specified unit. + public PowerRatio ToUnit(PowerRatioUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new PowerRatio(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerRatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == PowerRatioUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerRatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; + case PowerRatioUnit.DecibelWatt: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs index 8fa62caa0e..822ae55360 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,393 +49,706 @@ namespace UnitsNet /// /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Pressure : IComparable, IComparable + public partial struct Pressure : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Pressure from nullable Atmospheres. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromAtmospheres(QuantityValue? atmospheres) + private readonly PressureUnit? _unit; + + static Pressure() { - return atmospheres.HasValue ? FromAtmospheres(atmospheres.Value) : default(Pressure?); + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable Pressure from nullable Bars. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromBars(QuantityValue? bars) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Pressure(double numericValue, PressureUnit unit) { - return bars.HasValue ? FromBars(bars.Value) : default(Pressure?); + if(unit == PressureUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Pressure, which is Pascal. All conversions go via this value. + /// + public static PressureUnit BaseUnit => PressureUnit.Pascal; + + /// + /// Represents the largest possible value of Pressure + /// + public static Pressure MaxValue => new Pressure(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Pressure + /// + public static Pressure MinValue => new Pressure(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Pressure; + + /// + /// All units of measurement for the Pressure quantity. + /// + public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. + /// + public static Pressure Zero => new Pressure(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Pressure.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Pressure.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Pressure in Atmospheres. + /// + public double Atmospheres => As(PressureUnit.Atmosphere); + + /// + /// Get Pressure in Bars. + /// + public double Bars => As(PressureUnit.Bar); + + /// + /// Get Pressure in Centibars. + /// + public double Centibars => As(PressureUnit.Centibar); + + /// + /// Get Pressure in Decapascals. + /// + public double Decapascals => As(PressureUnit.Decapascal); + + /// + /// Get Pressure in Decibars. + /// + public double Decibars => As(PressureUnit.Decibar); + + /// + /// Get Pressure in DynesPerSquareCentimeter. + /// + public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + + /// + /// Get Pressure in FeetOfHead. + /// + public double FeetOfHead => As(PressureUnit.FootOfHead); + + /// + /// Get Pressure in Gigapascals. + /// + public double Gigapascals => As(PressureUnit.Gigapascal); + + /// + /// Get Pressure in Hectopascals. + /// + public double Hectopascals => As(PressureUnit.Hectopascal); + + /// + /// Get Pressure in InchesOfMercury. + /// + public double InchesOfMercury => As(PressureUnit.InchOfMercury); + + /// + /// Get Pressure in Kilobars. + /// + public double Kilobars => As(PressureUnit.Kilobar); + + /// + /// Get Pressure in KilogramsForcePerSquareCentimeter. + /// + public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); + + /// + /// Get Pressure in KilogramsForcePerSquareMeter. + /// + public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); + + /// + /// Get Pressure in KilogramsForcePerSquareMillimeter. + /// + public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); + + /// + /// Get Pressure in KilonewtonsPerSquareCentimeter. + /// + public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); + + /// + /// Get Pressure in KilonewtonsPerSquareMeter. + /// + public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); + + /// + /// Get Pressure in KilonewtonsPerSquareMillimeter. + /// + public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); + + /// + /// Get Pressure in Kilopascals. + /// + public double Kilopascals => As(PressureUnit.Kilopascal); + + /// + /// Get Pressure in KilopoundsForcePerSquareFoot. + /// + public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); + + /// + /// Get Pressure in KilopoundsForcePerSquareInch. + /// + public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); + /// - /// Get nullable Pressure from nullable Centibars. + /// Get Pressure in Megabars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromCentibars(QuantityValue? centibars) + public double Megabars => As(PressureUnit.Megabar); + + /// + /// Get Pressure in MeganewtonsPerSquareMeter. + /// + public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); + + /// + /// Get Pressure in Megapascals. + /// + public double Megapascals => As(PressureUnit.Megapascal); + + /// + /// Get Pressure in MetersOfHead. + /// + public double MetersOfHead => As(PressureUnit.MeterOfHead); + + /// + /// Get Pressure in Microbars. + /// + public double Microbars => As(PressureUnit.Microbar); + + /// + /// Get Pressure in Micropascals. + /// + public double Micropascals => As(PressureUnit.Micropascal); + + /// + /// Get Pressure in Millibars. + /// + public double Millibars => As(PressureUnit.Millibar); + + /// + /// Get Pressure in MillimetersOfMercury. + /// + public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); + + /// + /// Get Pressure in Millipascals. + /// + public double Millipascals => As(PressureUnit.Millipascal); + + /// + /// Get Pressure in NewtonsPerSquareCentimeter. + /// + public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); + + /// + /// Get Pressure in NewtonsPerSquareMeter. + /// + public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); + + /// + /// Get Pressure in NewtonsPerSquareMillimeter. + /// + public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); + + /// + /// Get Pressure in Pascals. + /// + public double Pascals => As(PressureUnit.Pascal); + + /// + /// Get Pressure in PoundsForcePerSquareFoot. + /// + public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); + + /// + /// Get Pressure in PoundsForcePerSquareInch. + /// + public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); + + /// + /// Get Pressure in PoundsPerInchSecondSquared. + /// + public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + + /// + /// Get Pressure in TechnicalAtmospheres. + /// + public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); + + /// + /// Get Pressure in TonnesForcePerSquareCentimeter. + /// + public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); + + /// + /// Get Pressure in TonnesForcePerSquareMeter. + /// + public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); + + /// + /// Get Pressure in TonnesForcePerSquareMillimeter. + /// + public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); + + /// + /// Get Pressure in Torrs. + /// + public double Torrs => As(PressureUnit.Torr); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureUnit unit) { - return centibars.HasValue ? FromCentibars(centibars.Value) : default(Pressure?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Pressure from nullable Decapascals. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromDecapascals(QuantityValue? decapascals) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PressureUnit unit, [CanBeNull] IFormatProvider provider) { - return decapascals.HasValue ? FromDecapascals(decapascals.Value) : default(Pressure?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Pressure from nullable Decibars. + /// Get Pressure from Atmospheres. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromDecibars(QuantityValue? decibars) + /// If value is NaN or Infinity. + public static Pressure FromAtmospheres(QuantityValue atmospheres) { - return decibars.HasValue ? FromDecibars(decibars.Value) : default(Pressure?); + double value = (double) atmospheres; + return new Pressure(value, PressureUnit.Atmosphere); } - /// - /// Get nullable Pressure from nullable DynesPerSquareCentimeter. + /// Get Pressure from Bars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromDynesPerSquareCentimeter(QuantityValue? dynespersquarecentimeter) + /// If value is NaN or Infinity. + public static Pressure FromBars(QuantityValue bars) { - return dynespersquarecentimeter.HasValue ? FromDynesPerSquareCentimeter(dynespersquarecentimeter.Value) : default(Pressure?); + double value = (double) bars; + return new Pressure(value, PressureUnit.Bar); } - /// - /// Get nullable Pressure from nullable FeetOfHead. + /// Get Pressure from Centibars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromFeetOfHead(QuantityValue? feetofhead) + /// If value is NaN or Infinity. + public static Pressure FromCentibars(QuantityValue centibars) { - return feetofhead.HasValue ? FromFeetOfHead(feetofhead.Value) : default(Pressure?); + double value = (double) centibars; + return new Pressure(value, PressureUnit.Centibar); } - /// - /// Get nullable Pressure from nullable Gigapascals. + /// Get Pressure from Decapascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromGigapascals(QuantityValue? gigapascals) + /// If value is NaN or Infinity. + public static Pressure FromDecapascals(QuantityValue decapascals) { - return gigapascals.HasValue ? FromGigapascals(gigapascals.Value) : default(Pressure?); + double value = (double) decapascals; + return new Pressure(value, PressureUnit.Decapascal); } - /// - /// Get nullable Pressure from nullable Hectopascals. + /// Get Pressure from Decibars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromHectopascals(QuantityValue? hectopascals) + /// If value is NaN or Infinity. + public static Pressure FromDecibars(QuantityValue decibars) { - return hectopascals.HasValue ? FromHectopascals(hectopascals.Value) : default(Pressure?); + double value = (double) decibars; + return new Pressure(value, PressureUnit.Decibar); } - /// - /// Get nullable Pressure from nullable InchesOfMercury. + /// Get Pressure from DynesPerSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromInchesOfMercury(QuantityValue? inchesofmercury) + /// If value is NaN or Infinity. + public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquarecentimeter) { - return inchesofmercury.HasValue ? FromInchesOfMercury(inchesofmercury.Value) : default(Pressure?); + double value = (double) dynespersquarecentimeter; + return new Pressure(value, PressureUnit.DynePerSquareCentimeter); } - /// - /// Get nullable Pressure from nullable Kilobars. + /// Get Pressure from FeetOfHead. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilobars(QuantityValue? kilobars) + /// If value is NaN or Infinity. + public static Pressure FromFeetOfHead(QuantityValue feetofhead) { - return kilobars.HasValue ? FromKilobars(kilobars.Value) : default(Pressure?); + double value = (double) feetofhead; + return new Pressure(value, PressureUnit.FootOfHead); } - /// - /// Get nullable Pressure from nullable KilogramsForcePerSquareCentimeter. + /// Get Pressure from Gigapascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilogramsForcePerSquareCentimeter(QuantityValue? kilogramsforcepersquarecentimeter) + /// If value is NaN or Infinity. + public static Pressure FromGigapascals(QuantityValue gigapascals) { - return kilogramsforcepersquarecentimeter.HasValue ? FromKilogramsForcePerSquareCentimeter(kilogramsforcepersquarecentimeter.Value) : default(Pressure?); + double value = (double) gigapascals; + return new Pressure(value, PressureUnit.Gigapascal); } - /// - /// Get nullable Pressure from nullable KilogramsForcePerSquareMeter. + /// Get Pressure from Hectopascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilogramsForcePerSquareMeter(QuantityValue? kilogramsforcepersquaremeter) + /// If value is NaN or Infinity. + public static Pressure FromHectopascals(QuantityValue hectopascals) { - return kilogramsforcepersquaremeter.HasValue ? FromKilogramsForcePerSquareMeter(kilogramsforcepersquaremeter.Value) : default(Pressure?); + double value = (double) hectopascals; + return new Pressure(value, PressureUnit.Hectopascal); } - /// - /// Get nullable Pressure from nullable KilogramsForcePerSquareMillimeter. + /// Get Pressure from InchesOfMercury. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilogramsForcePerSquareMillimeter(QuantityValue? kilogramsforcepersquaremillimeter) + /// If value is NaN or Infinity. + public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) { - return kilogramsforcepersquaremillimeter.HasValue ? FromKilogramsForcePerSquareMillimeter(kilogramsforcepersquaremillimeter.Value) : default(Pressure?); + double value = (double) inchesofmercury; + return new Pressure(value, PressureUnit.InchOfMercury); } - /// - /// Get nullable Pressure from nullable KilonewtonsPerSquareCentimeter. + /// Get Pressure from Kilobars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilonewtonsPerSquareCentimeter(QuantityValue? kilonewtonspersquarecentimeter) + /// If value is NaN or Infinity. + public static Pressure FromKilobars(QuantityValue kilobars) { - return kilonewtonspersquarecentimeter.HasValue ? FromKilonewtonsPerSquareCentimeter(kilonewtonspersquarecentimeter.Value) : default(Pressure?); + double value = (double) kilobars; + return new Pressure(value, PressureUnit.Kilobar); } - /// - /// Get nullable Pressure from nullable KilonewtonsPerSquareMeter. + /// Get Pressure from KilogramsForcePerSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilonewtonsPerSquareMeter(QuantityValue? kilonewtonspersquaremeter) + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) { - return kilonewtonspersquaremeter.HasValue ? FromKilonewtonsPerSquareMeter(kilonewtonspersquaremeter.Value) : default(Pressure?); + double value = (double) kilogramsforcepersquarecentimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); } - /// - /// Get nullable Pressure from nullable KilonewtonsPerSquareMillimeter. + /// Get Pressure from KilogramsForcePerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilonewtonsPerSquareMillimeter(QuantityValue? kilonewtonspersquaremillimeter) + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) { - return kilonewtonspersquaremillimeter.HasValue ? FromKilonewtonsPerSquareMillimeter(kilonewtonspersquaremillimeter.Value) : default(Pressure?); + double value = (double) kilogramsforcepersquaremeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); } - /// - /// Get nullable Pressure from nullable Kilopascals. + /// Get Pressure from KilogramsForcePerSquareMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilopascals(QuantityValue? kilopascals) + /// If value is NaN or Infinity. + public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) { - return kilopascals.HasValue ? FromKilopascals(kilopascals.Value) : default(Pressure?); + double value = (double) kilogramsforcepersquaremillimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); } - /// - /// Get nullable Pressure from nullable KilopoundsForcePerSquareFoot. + /// Get Pressure from KilonewtonsPerSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilopoundsForcePerSquareFoot(QuantityValue? kilopoundsforcepersquarefoot) + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) { - return kilopoundsforcepersquarefoot.HasValue ? FromKilopoundsForcePerSquareFoot(kilopoundsforcepersquarefoot.Value) : default(Pressure?); + double value = (double) kilonewtonspersquarecentimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); } - /// - /// Get nullable Pressure from nullable KilopoundsForcePerSquareInch. + /// Get Pressure from KilonewtonsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromKilopoundsForcePerSquareInch(QuantityValue? kilopoundsforcepersquareinch) + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) { - return kilopoundsforcepersquareinch.HasValue ? FromKilopoundsForcePerSquareInch(kilopoundsforcepersquareinch.Value) : default(Pressure?); + double value = (double) kilonewtonspersquaremeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); } - /// - /// Get nullable Pressure from nullable Megabars. + /// Get Pressure from KilonewtonsPerSquareMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMegabars(QuantityValue? megabars) + /// If value is NaN or Infinity. + public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) { - return megabars.HasValue ? FromMegabars(megabars.Value) : default(Pressure?); + double value = (double) kilonewtonspersquaremillimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); } - /// - /// Get nullable Pressure from nullable MeganewtonsPerSquareMeter. + /// Get Pressure from Kilopascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMeganewtonsPerSquareMeter(QuantityValue? meganewtonspersquaremeter) + /// If value is NaN or Infinity. + public static Pressure FromKilopascals(QuantityValue kilopascals) { - return meganewtonspersquaremeter.HasValue ? FromMeganewtonsPerSquareMeter(meganewtonspersquaremeter.Value) : default(Pressure?); + double value = (double) kilopascals; + return new Pressure(value, PressureUnit.Kilopascal); } - /// - /// Get nullable Pressure from nullable Megapascals. + /// Get Pressure from KilopoundsForcePerSquareFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMegapascals(QuantityValue? megapascals) + /// If value is NaN or Infinity. + public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) { - return megapascals.HasValue ? FromMegapascals(megapascals.Value) : default(Pressure?); + double value = (double) kilopoundsforcepersquarefoot; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); } - /// - /// Get nullable Pressure from nullable MetersOfHead. + /// Get Pressure from KilopoundsForcePerSquareInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMetersOfHead(QuantityValue? metersofhead) + /// If value is NaN or Infinity. + public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) { - return metersofhead.HasValue ? FromMetersOfHead(metersofhead.Value) : default(Pressure?); + double value = (double) kilopoundsforcepersquareinch; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); } - /// - /// Get nullable Pressure from nullable Microbars. + /// Get Pressure from Megabars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMicrobars(QuantityValue? microbars) + /// If value is NaN or Infinity. + public static Pressure FromMegabars(QuantityValue megabars) { - return microbars.HasValue ? FromMicrobars(microbars.Value) : default(Pressure?); + double value = (double) megabars; + return new Pressure(value, PressureUnit.Megabar); } - /// - /// Get nullable Pressure from nullable Micropascals. + /// Get Pressure from MeganewtonsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMicropascals(QuantityValue? micropascals) + /// If value is NaN or Infinity. + public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) { - return micropascals.HasValue ? FromMicropascals(micropascals.Value) : default(Pressure?); + double value = (double) meganewtonspersquaremeter; + return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); } - /// - /// Get nullable Pressure from nullable Millibars. + /// Get Pressure from Megapascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMillibars(QuantityValue? millibars) + /// If value is NaN or Infinity. + public static Pressure FromMegapascals(QuantityValue megapascals) { - return millibars.HasValue ? FromMillibars(millibars.Value) : default(Pressure?); + double value = (double) megapascals; + return new Pressure(value, PressureUnit.Megapascal); } - /// - /// Get nullable Pressure from nullable MillimetersOfMercury. + /// Get Pressure from MetersOfHead. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMillimetersOfMercury(QuantityValue? millimetersofmercury) + /// If value is NaN or Infinity. + public static Pressure FromMetersOfHead(QuantityValue metersofhead) { - return millimetersofmercury.HasValue ? FromMillimetersOfMercury(millimetersofmercury.Value) : default(Pressure?); + double value = (double) metersofhead; + return new Pressure(value, PressureUnit.MeterOfHead); } - /// - /// Get nullable Pressure from nullable Millipascals. + /// Get Pressure from Microbars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromMillipascals(QuantityValue? millipascals) + /// If value is NaN or Infinity. + public static Pressure FromMicrobars(QuantityValue microbars) { - return millipascals.HasValue ? FromMillipascals(millipascals.Value) : default(Pressure?); + double value = (double) microbars; + return new Pressure(value, PressureUnit.Microbar); } - /// - /// Get nullable Pressure from nullable NewtonsPerSquareCentimeter. + /// Get Pressure from Micropascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromNewtonsPerSquareCentimeter(QuantityValue? newtonspersquarecentimeter) + /// If value is NaN or Infinity. + public static Pressure FromMicropascals(QuantityValue micropascals) { - return newtonspersquarecentimeter.HasValue ? FromNewtonsPerSquareCentimeter(newtonspersquarecentimeter.Value) : default(Pressure?); + double value = (double) micropascals; + return new Pressure(value, PressureUnit.Micropascal); } - /// - /// Get nullable Pressure from nullable NewtonsPerSquareMeter. + /// Get Pressure from Millibars. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromNewtonsPerSquareMeter(QuantityValue? newtonspersquaremeter) + /// If value is NaN or Infinity. + public static Pressure FromMillibars(QuantityValue millibars) { - return newtonspersquaremeter.HasValue ? FromNewtonsPerSquareMeter(newtonspersquaremeter.Value) : default(Pressure?); + double value = (double) millibars; + return new Pressure(value, PressureUnit.Millibar); } - /// - /// Get nullable Pressure from nullable NewtonsPerSquareMillimeter. + /// Get Pressure from MillimetersOfMercury. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromNewtonsPerSquareMillimeter(QuantityValue? newtonspersquaremillimeter) + /// If value is NaN or Infinity. + public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) { - return newtonspersquaremillimeter.HasValue ? FromNewtonsPerSquareMillimeter(newtonspersquaremillimeter.Value) : default(Pressure?); + double value = (double) millimetersofmercury; + return new Pressure(value, PressureUnit.MillimeterOfMercury); } - /// - /// Get nullable Pressure from nullable Pascals. + /// Get Pressure from Millipascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromPascals(QuantityValue? pascals) + /// If value is NaN or Infinity. + public static Pressure FromMillipascals(QuantityValue millipascals) { - return pascals.HasValue ? FromPascals(pascals.Value) : default(Pressure?); + double value = (double) millipascals; + return new Pressure(value, PressureUnit.Millipascal); } - /// - /// Get nullable Pressure from nullable PoundsForcePerSquareFoot. + /// Get Pressure from NewtonsPerSquareCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromPoundsForcePerSquareFoot(QuantityValue? poundsforcepersquarefoot) + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) { - return poundsforcepersquarefoot.HasValue ? FromPoundsForcePerSquareFoot(poundsforcepersquarefoot.Value) : default(Pressure?); + double value = (double) newtonspersquarecentimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); } - /// - /// Get nullable Pressure from nullable PoundsForcePerSquareInch. + /// Get Pressure from NewtonsPerSquareMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromPoundsForcePerSquareInch(QuantityValue? poundsforcepersquareinch) + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) { - return poundsforcepersquareinch.HasValue ? FromPoundsForcePerSquareInch(poundsforcepersquareinch.Value) : default(Pressure?); + double value = (double) newtonspersquaremeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); } - /// - /// Get nullable Pressure from nullable PoundsPerInchSecondSquared. + /// Get Pressure from NewtonsPerSquareMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromPoundsPerInchSecondSquared(QuantityValue? poundsperinchsecondsquared) + /// If value is NaN or Infinity. + public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) { - return poundsperinchsecondsquared.HasValue ? FromPoundsPerInchSecondSquared(poundsperinchsecondsquared.Value) : default(Pressure?); + double value = (double) newtonspersquaremillimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); } - /// - /// Get nullable Pressure from nullable Psi. + /// Get Pressure from Pascals. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromPsi(QuantityValue? psi) + /// If value is NaN or Infinity. + public static Pressure FromPascals(QuantityValue pascals) { - return psi.HasValue ? FromPsi(psi.Value) : default(Pressure?); + double value = (double) pascals; + return new Pressure(value, PressureUnit.Pascal); } - /// - /// Get nullable Pressure from nullable TechnicalAtmospheres. + /// Get Pressure from PoundsForcePerSquareFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromTechnicalAtmospheres(QuantityValue? technicalatmospheres) + /// If value is NaN or Infinity. + public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) { - return technicalatmospheres.HasValue ? FromTechnicalAtmospheres(technicalatmospheres.Value) : default(Pressure?); + double value = (double) poundsforcepersquarefoot; + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); } - /// - /// Get nullable Pressure from nullable TonnesForcePerSquareCentimeter. + /// Get Pressure from PoundsForcePerSquareInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromTonnesForcePerSquareCentimeter(QuantityValue? tonnesforcepersquarecentimeter) + /// If value is NaN or Infinity. + public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) { - return tonnesforcepersquarecentimeter.HasValue ? FromTonnesForcePerSquareCentimeter(tonnesforcepersquarecentimeter.Value) : default(Pressure?); + double value = (double) poundsforcepersquareinch; + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); } - /// - /// Get nullable Pressure from nullable TonnesForcePerSquareMeter. + /// Get Pressure from PoundsPerInchSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromTonnesForcePerSquareMeter(QuantityValue? tonnesforcepersquaremeter) + /// If value is NaN or Infinity. + public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinchsecondsquared) { - return tonnesforcepersquaremeter.HasValue ? FromTonnesForcePerSquareMeter(tonnesforcepersquaremeter.Value) : default(Pressure?); + double value = (double) poundsperinchsecondsquared; + return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); } - /// - /// Get nullable Pressure from nullable TonnesForcePerSquareMillimeter. + /// Get Pressure from TechnicalAtmospheres. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromTonnesForcePerSquareMillimeter(QuantityValue? tonnesforcepersquaremillimeter) + /// If value is NaN or Infinity. + public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) { - return tonnesforcepersquaremillimeter.HasValue ? FromTonnesForcePerSquareMillimeter(tonnesforcepersquaremillimeter.Value) : default(Pressure?); + double value = (double) technicalatmospheres; + return new Pressure(value, PressureUnit.TechnicalAtmosphere); + } + /// + /// Get Pressure from TonnesForcePerSquareCentimeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) + { + double value = (double) tonnesforcepersquarecentimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); + } + /// + /// Get Pressure from TonnesForcePerSquareMeter. + /// + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) + { + double value = (double) tonnesforcepersquaremeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); } - /// - /// Get nullable Pressure from nullable Torrs. + /// Get Pressure from TonnesForcePerSquareMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Pressure? FromTorrs(QuantityValue? torrs) + /// If value is NaN or Infinity. + public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) { - return torrs.HasValue ? FromTorrs(torrs.Value) : default(Pressure?); + double value = (double) tonnesforcepersquaremillimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); + } + /// + /// Get Pressure from Torrs. + /// + /// If value is NaN or Infinity. + public static Pressure FromTorrs(QuantityValue torrs) + { + double value = (double) torrs; + return new Pressure(value, PressureUnit.Torr); } /// @@ -446,28 +757,156 @@ public partial struct Pressure : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Pressure unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Pressure? From(QuantityValue? value, PressureUnit fromUnit) + public static Pressure From(QuantityValue value, PressureUnit fromUnit) { - return value.HasValue ? new Pressure((double)value.Value, fromUnit) : default(Pressure?); + return new Pressure((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static Pressure Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Pressure Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Pressure result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Pressure result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PressureUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PressureUnit ParseUnit(string str, IFormatProvider provider = null) { - provider = provider ?? UnitSystem.DefaultCulture; + return UnitParser.Default.Parse(str, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + public static bool TryParseUnit(string str, out PressureUnit unit) + { + return TryParseUnit(str, null, out unit); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PressureUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Pressure operator -(Pressure right) @@ -507,6 +946,8 @@ public static string GetAbbreviation(PressureUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(Pressure left, Pressure right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -527,180 +968,296 @@ public static string GetAbbreviation(PressureUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Pressure, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Pressure left, Pressure right) + public static bool operator ==(Pressure left, Pressure right) + { + return left.Equals(right); + } + + public static bool operator !=(Pressure left, Pressure right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Pressure, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Pressure left, Pressure right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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 + public int CompareTo(Pressure other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + public override bool Equals(object obj) + { + if(obj is null || !(obj is Pressure objPressure)) + return false; + + return Equals(objPressure); } - #region Parsing + public bool Equals(Pressure other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Pressure Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Pressure other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PressureUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromPascals(x.Pascals + y.Pascals)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Pressure result) + /// A hash code for the current Pressure. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Pressure); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Pressure to another Pressure with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Pressure with the specified unit. + public Pressure ToUnit(PressureUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Pressure(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case PressureUnit.Atmosphere: return _value*1.01325*1e5; + case PressureUnit.Bar: return _value*1e5; + case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; + case PressureUnit.Decapascal: return (_value) * 1e1d; + case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; + case PressureUnit.DynePerSquareCentimeter: return _value*1.0e-1; + case PressureUnit.FootOfHead: return _value*2989.0669; + case PressureUnit.Gigapascal: return (_value) * 1e9d; + case PressureUnit.Hectopascal: return (_value) * 1e2d; + case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; + case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665e4; + case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; + case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9.80665e6; + case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; + case PressureUnit.Kilopascal: return (_value) * 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (_value*4.788025898033584e1) * 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (_value*6.894757293168361e3) * 1e3d; + case PressureUnit.Megabar: return (_value*1e5) * 1e6d; + case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; + case PressureUnit.Megapascal: return (_value) * 1e6d; + case PressureUnit.MeterOfHead: return _value*9804.139432; + case PressureUnit.Microbar: return (_value*1e5) * 1e-6d; + case PressureUnit.Micropascal: return (_value) * 1e-6d; + case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; + case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; + case PressureUnit.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.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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(PressureUnit unit) + { + if(Unit == unit) + return _value; - if (unit == PressureUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); + case PressureUnit.Bar: return baseUnitValue/1e5; + case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; + case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; + case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; + case PressureUnit.DynePerSquareCentimeter: return baseUnitValue/1.0e-1; + case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; + case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; + case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; + case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; + case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/9.80665e4; + case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; + case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue/9.80665e6; + case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; + case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue/4.788025898033584e1) / 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue/6.894757293168361e3) / 1e3d; + case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; + case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; + case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; + case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; + case PressureUnit.Microbar: return (baseUnitValue/1e5) / 1e-6d; + case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; + case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; + case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; + case PressureUnit.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.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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PressureUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs index 1dfe791ce2..eebe52221b 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,188 @@ namespace UnitsNet /// /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct PressureChangeRate : IComparable, IComparable + public partial struct PressureChangeRate : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureChangeRateUnit? _unit; + + static PressureChangeRate() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + } /// - /// Get nullable PressureChangeRate from nullable AtmospheresPerSecond. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PressureChangeRate? FromAtmospheresPerSecond(QuantityValue? atmospherespersecond) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public PressureChangeRate(double numericValue, PressureChangeRateUnit unit) { - return atmospherespersecond.HasValue ? FromAtmospheresPerSecond(atmospherespersecond.Value) : default(PressureChangeRate?); + if(unit == PressureChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. + /// + public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; + + /// + /// Represents the largest possible value of PressureChangeRate + /// + public static PressureChangeRate MaxValue => new PressureChangeRate(double.MaxValue, BaseUnit); + /// - /// Get nullable PressureChangeRate from nullable KilopascalsPerSecond. + /// Represents the smallest possible value of PressureChangeRate /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PressureChangeRate? FromKilopascalsPerSecond(QuantityValue? kilopascalspersecond) + public static PressureChangeRate MinValue => new PressureChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.PressureChangeRate; + + /// + /// All units of measurement for the PressureChangeRate quantity. + /// + public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. + /// + public static PressureChangeRate Zero => new PressureChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => PressureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get PressureChangeRate in AtmospheresPerSecond. + /// + public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); + + /// + /// Get PressureChangeRate in KilopascalsPerSecond. + /// + public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); + + /// + /// Get PressureChangeRate in MegapascalsPerSecond. + /// + public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); + + /// + /// Get PressureChangeRate in PascalsPerSecond. + /// + public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(PressureChangeRateUnit unit) { - return kilopascalspersecond.HasValue ? FromKilopascalsPerSecond(kilopascalspersecond.Value) : default(PressureChangeRate?); + return GetAbbreviation(unit, null); } /// - /// Get nullable PressureChangeRate from nullable MegapascalsPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PressureChangeRate? FromMegapascalsPerSecond(QuantityValue? megapascalspersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) { - return megapascalspersecond.HasValue ? FromMegapascalsPerSecond(megapascalspersecond.Value) : default(PressureChangeRate?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get PressureChangeRate from AtmospheresPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) + { + double value = (double) atmospherespersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); + } + /// + /// Get PressureChangeRate from KilopascalsPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) + { + double value = (double) kilopascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); + } /// - /// Get nullable PressureChangeRate from nullable PascalsPerSecond. + /// Get PressureChangeRate from MegapascalsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static PressureChangeRate? FromPascalsPerSecond(QuantityValue? pascalspersecond) + /// If value is NaN or Infinity. + public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) { - return pascalspersecond.HasValue ? FromPascalsPerSecond(pascalspersecond.Value) : default(PressureChangeRate?); + double value = (double) megapascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); + } + /// + /// Get PressureChangeRate from PascalsPerSecond. + /// + /// If value is NaN or Infinity. + public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) + { + double value = (double) pascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); } /// @@ -104,28 +239,156 @@ public partial struct PressureChangeRate : IComparable, IComparableValue to convert from. /// Unit to convert from. /// PressureChangeRate unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static PressureChangeRate? From(QuantityValue? value, PressureChangeRateUnit fromUnit) + public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) { - return value.HasValue ? new PressureChangeRate((double)value.Value, fromUnit) : default(PressureChangeRate?); + return new PressureChangeRate((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static PressureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PressureChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static PressureChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static PressureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out PressureChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static PressureChangeRate operator -(PressureChangeRate right) @@ -165,6 +428,8 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] IF #endregion + #region Equality / IComparable + public static bool operator <=(PressureChangeRate left, PressureChangeRate right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +450,222 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] IF return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PressureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(PressureChangeRate left, PressureChangeRate right) + public static bool operator ==(PressureChangeRate left, PressureChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(PressureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(PressureChangeRate left, PressureChangeRate right) + public static bool operator !=(PressureChangeRate left, PressureChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(PressureChangeRate other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PressureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(PressureChangeRate other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - PressureChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromPascalsPerSecond(x.PascalsPerSecond + y.PascalsPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out PressureChangeRate result) + /// A hash code for the current PressureChangeRate. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(PressureChangeRate); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A PressureChangeRate with the specified unit. + public PressureChangeRate ToUnit(PressureChangeRateUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new PressureChangeRate(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; + case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(PressureChangeRateUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == PressureChangeRateUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); + case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs index 40a9bc9533..3162555801 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,69 +49,216 @@ namespace UnitsNet /// /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Ratio : IComparable, IComparable + public partial struct Ratio : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Ratio from nullable DecimalFractions. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromDecimalFractions(QuantityValue? decimalfractions) + private readonly RatioUnit? _unit; + + static Ratio() { - return decimalfractions.HasValue ? FromDecimalFractions(decimalfractions.Value) : default(Ratio?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable Ratio from nullable PartsPerBillion. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromPartsPerBillion(QuantityValue? partsperbillion) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Ratio(double numericValue, RatioUnit unit) { - return partsperbillion.HasValue ? FromPartsPerBillion(partsperbillion.Value) : default(Ratio?); + if(unit == RatioUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + /// - /// Get nullable Ratio from nullable PartsPerMillion. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromPartsPerMillion(QuantityValue? partspermillion) + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. + /// + public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; + + /// + /// Represents the largest possible value of Ratio + /// + public static Ratio MaxValue => new Ratio(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Ratio + /// + public static Ratio MinValue => new Ratio(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Ratio; + + /// + /// All units of measurement for the Ratio quantity. + /// + public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// + public static Ratio Zero => new Ratio(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Ratio.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Ratio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Ratio in DecimalFractions. + /// + public double DecimalFractions => As(RatioUnit.DecimalFraction); + + /// + /// Get Ratio in PartsPerBillion. + /// + public double PartsPerBillion => As(RatioUnit.PartPerBillion); + + /// + /// Get Ratio in PartsPerMillion. + /// + public double PartsPerMillion => As(RatioUnit.PartPerMillion); + + /// + /// Get Ratio in PartsPerThousand. + /// + public double PartsPerThousand => As(RatioUnit.PartPerThousand); + + /// + /// Get Ratio in PartsPerTrillion. + /// + public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); + + /// + /// Get Ratio in Percent. + /// + public double Percent => As(RatioUnit.Percent); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RatioUnit unit) { - return partspermillion.HasValue ? FromPartsPerMillion(partspermillion.Value) : default(Ratio?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Ratio from nullable PartsPerThousand. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromPartsPerThousand(QuantityValue? partsperthousand) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(RatioUnit unit, [CanBeNull] IFormatProvider provider) { - return partsperthousand.HasValue ? FromPartsPerThousand(partsperthousand.Value) : default(Ratio?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Ratio from nullable PartsPerTrillion. + /// Get Ratio from DecimalFractions. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromPartsPerTrillion(QuantityValue? partspertrillion) + /// If value is NaN or Infinity. + public static Ratio FromDecimalFractions(QuantityValue decimalfractions) { - return partspertrillion.HasValue ? FromPartsPerTrillion(partspertrillion.Value) : default(Ratio?); + double value = (double) decimalfractions; + return new Ratio(value, RatioUnit.DecimalFraction); + } + /// + /// Get Ratio from PartsPerBillion. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) + { + double value = (double) partsperbillion; + return new Ratio(value, RatioUnit.PartPerBillion); } - /// - /// Get nullable Ratio from nullable Percent. + /// Get Ratio from PartsPerMillion. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Ratio? FromPercent(QuantityValue? percent) + /// If value is NaN or Infinity. + public static Ratio FromPartsPerMillion(QuantityValue partspermillion) { - return percent.HasValue ? FromPercent(percent.Value) : default(Ratio?); + double value = (double) partspermillion; + return new Ratio(value, RatioUnit.PartPerMillion); + } + /// + /// Get Ratio from PartsPerThousand. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) + { + double value = (double) partsperthousand; + return new Ratio(value, RatioUnit.PartPerThousand); + } + /// + /// Get Ratio from PartsPerTrillion. + /// + /// If value is NaN or Infinity. + public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) + { + double value = (double) partspertrillion; + return new Ratio(value, RatioUnit.PartPerTrillion); + } + /// + /// Get Ratio from Percent. + /// + /// If value is NaN or Infinity. + public static Ratio FromPercent(QuantityValue percent) + { + double value = (double) percent; + return new Ratio(value, RatioUnit.Percent); } /// @@ -122,28 +267,156 @@ public partial struct Ratio : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Ratio unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Ratio? From(QuantityValue? value, RatioUnit fromUnit) + public static Ratio From(QuantityValue value, RatioUnit fromUnit) { - return value.HasValue ? new Ratio((double)value.Value, fromUnit) : default(Ratio?); + return new Ratio((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RatioUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Ratio Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Ratio result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Ratio result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static RatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static RatioUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out RatioUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Ratio operator -(Ratio right) @@ -183,6 +456,8 @@ public static string GetAbbreviation(RatioUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Ratio left, Ratio right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -203,180 +478,226 @@ public static string GetAbbreviation(RatioUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Ratio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Ratio left, Ratio right) + public static bool operator ==(Ratio left, Ratio right) + { + return left.Equals(right); + } + + public static bool operator !=(Ratio left, Ratio right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); + } + + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Ratio, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Ratio left, Ratio right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Ratio other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Ratio Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RatioUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDecimalFractions(x.DecimalFractions + y.DecimalFractions)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Ratio result) + /// A hash code for the current Ratio. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Ratio); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RatioUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Ratio to another Ratio with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Ratio with the specified unit. + public Ratio ToUnit(RatioUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Ratio(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RatioUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == RatioUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RatioUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(RatioUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs index b2ede6bf91..11a5edac93 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ReactiveEnergy : IComparable, IComparable + public partial struct ReactiveEnergy : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactiveEnergyUnit? _unit; + + static ReactiveEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ReactiveEnergy(double numericValue, ReactiveEnergyUnit unit) + { + if(unit == ReactiveEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. + /// + public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; + + /// + /// Represents the largest possible value of ReactiveEnergy + /// + public static ReactiveEnergy MaxValue => new ReactiveEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ReactiveEnergy + /// + public static ReactiveEnergy MinValue => new ReactiveEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ReactiveEnergy; + + /// + /// All units of measurement for the ReactiveEnergy quantity. + /// + public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// + public static ReactiveEnergy Zero => new ReactiveEnergy(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactiveEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable ReactiveEnergy from nullable KilovoltampereReactiveHours. + /// Get ReactiveEnergy in KilovoltampereReactiveHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactiveEnergy? FromKilovoltampereReactiveHours(QuantityValue? kilovoltamperereactivehours) + public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); + + /// + /// Get ReactiveEnergy in MegavoltampereReactiveHours. + /// + public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); + + /// + /// Get ReactiveEnergy in VoltampereReactiveHours. + /// + public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactiveEnergyUnit unit) { - return kilovoltamperereactivehours.HasValue ? FromKilovoltampereReactiveHours(kilovoltamperereactivehours.Value) : default(ReactiveEnergy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ReactiveEnergy from nullable MegavoltampereReactiveHours. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactiveEnergy? FromMegavoltampereReactiveHours(QuantityValue? megavoltamperereactivehours) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider) { - return megavoltamperereactivehours.HasValue ? FromMegavoltampereReactiveHours(megavoltamperereactivehours.Value) : default(ReactiveEnergy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ReactiveEnergy from KilovoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) + { + double value = (double) kilovoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); + } /// - /// Get nullable ReactiveEnergy from nullable VoltampereReactiveHours. + /// Get ReactiveEnergy from MegavoltampereReactiveHours. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactiveEnergy? FromVoltampereReactiveHours(QuantityValue? voltamperereactivehours) + /// If value is NaN or Infinity. + public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) { - return voltamperereactivehours.HasValue ? FromVoltampereReactiveHours(voltamperereactivehours.Value) : default(ReactiveEnergy?); + double value = (double) megavoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); + } + /// + /// Get ReactiveEnergy from VoltampereReactiveHours. + /// + /// If value is NaN or Infinity. + public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) + { + double value = (double) voltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); } /// @@ -95,28 +225,156 @@ public partial struct ReactiveEnergy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ReactiveEnergy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactiveEnergy? From(QuantityValue? value, ReactiveEnergyUnit fromUnit) + public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) { - return value.HasValue ? new ReactiveEnergy((double)value.Value, fromUnit) : default(ReactiveEnergy?); + return new ReactiveEnergy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ReactiveEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactiveEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ReactiveEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ReactiveEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ReactiveEnergy operator -(ReactiveEnergy right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(ReactiveEnergy left, ReactiveEnergy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactiveEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) + public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactiveEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) + public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ReactiveEnergy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactiveEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ReactiveEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltampereReactiveHours(x.VoltampereReactiveHours + y.VoltampereReactiveHours)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactiveEnergy result) + /// A hash code for the current ReactiveEnergy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ReactiveEnergy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactiveEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ReactiveEnergy with the specified unit. + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ReactiveEnergy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ReactiveEnergyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactiveEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs index c78d1a3a87..aa09b88dd1 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,51 +49,188 @@ namespace UnitsNet /// /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ReactivePower : IComparable, IComparable + public partial struct ReactivePower : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; + private readonly double _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactivePowerUnit? _unit; + + static ReactivePower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + } /// - /// Get nullable ReactivePower from nullable GigavoltamperesReactive. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactivePower? FromGigavoltamperesReactive(QuantityValue? gigavoltamperesreactive) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ReactivePower(double numericValue, ReactivePowerUnit unit) { - return gigavoltamperesreactive.HasValue ? FromGigavoltamperesReactive(gigavoltamperesreactive.Value) : default(ReactivePower?); + if(unit == ReactivePowerUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. + /// + public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; + + /// + /// Represents the largest possible value of ReactivePower + /// + public static ReactivePower MaxValue => new ReactivePower(double.MaxValue, BaseUnit); + /// - /// Get nullable ReactivePower from nullable KilovoltamperesReactive. + /// Represents the smallest possible value of ReactivePower /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactivePower? FromKilovoltamperesReactive(QuantityValue? kilovoltamperesreactive) + public static ReactivePower MinValue => new ReactivePower(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ReactivePower; + + /// + /// All units of measurement for the ReactivePower quantity. + /// + public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. + /// + public static ReactivePower Zero => new ReactivePower(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ReactivePower.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ReactivePower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ReactivePower in GigavoltamperesReactive. + /// + public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); + + /// + /// Get ReactivePower in KilovoltamperesReactive. + /// + public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); + + /// + /// Get ReactivePower in MegavoltamperesReactive. + /// + public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); + + /// + /// Get ReactivePower in VoltamperesReactive. + /// + public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ReactivePowerUnit unit) { - return kilovoltamperesreactive.HasValue ? FromKilovoltamperesReactive(kilovoltamperesreactive.Value) : default(ReactivePower?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ReactivePower from nullable MegavoltamperesReactive. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactivePower? FromMegavoltamperesReactive(QuantityValue? megavoltamperesreactive) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider) { - return megavoltamperesreactive.HasValue ? FromMegavoltamperesReactive(megavoltamperesreactive.Value) : default(ReactivePower?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ReactivePower from GigavoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) + { + double value = (double) gigavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); + } + /// + /// Get ReactivePower from KilovoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) + { + double value = (double) kilovoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); + } /// - /// Get nullable ReactivePower from nullable VoltamperesReactive. + /// Get ReactivePower from MegavoltamperesReactive. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ReactivePower? FromVoltamperesReactive(QuantityValue? voltamperesreactive) + /// If value is NaN or Infinity. + public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) { - return voltamperesreactive.HasValue ? FromVoltamperesReactive(voltamperesreactive.Value) : default(ReactivePower?); + double value = (double) megavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); + } + /// + /// Get ReactivePower from VoltamperesReactive. + /// + /// If value is NaN or Infinity. + public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) + { + double value = (double) voltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); } /// @@ -104,28 +239,156 @@ public partial struct ReactivePower : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// ReactivePower unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ReactivePower? From(QuantityValue? value, ReactivePowerUnit fromUnit) + public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) { - return value.HasValue ? new ReactivePower((double)value.Value, fromUnit) : default(ReactivePower?); + return new ReactivePower((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ReactivePower Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ReactivePower result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactivePower result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ReactivePowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ReactivePowerUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ReactivePowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ReactivePowerUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ReactivePower operator -(ReactivePower right) @@ -165,6 +428,8 @@ public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] IFormat #endregion + #region Equality / IComparable + public static bool operator <=(ReactivePower left, ReactivePower right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -185,180 +450,222 @@ public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] IFormat return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactivePower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ReactivePower left, ReactivePower right) + public static bool operator ==(ReactivePower left, ReactivePower right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ReactivePower, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ReactivePower left, ReactivePower right) + public static bool operator !=(ReactivePower left, ReactivePower right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ReactivePower other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactivePower Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ReactivePower other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ReactivePowerUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromVoltamperesReactive(x.VoltamperesReactive + y.VoltamperesReactive)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ReactivePower result) + /// A hash code for the current ReactivePower. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ReactivePower); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactivePowerUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ReactivePower to another ReactivePower with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ReactivePower with the specified unit. + public ReactivePower ToUnit(ReactivePowerUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ReactivePower(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactivePowerUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ReactivePowerUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactivePowerUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs index b358e20452..687e2d4e0e 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// Angular acceleration is the rate of change of rotational speed. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct RotationalAcceleration : IComparable, IComparable + public partial struct RotationalAcceleration : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalAccelerationUnit? _unit; + + static RotationalAcceleration() + { + BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public RotationalAcceleration(double numericValue, RotationalAccelerationUnit unit) + { + if(unit == RotationalAccelerationUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. + /// + public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; + + /// + /// Represents the largest possible value of RotationalAcceleration + /// + public static RotationalAcceleration MaxValue => new RotationalAcceleration(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalAcceleration + /// + public static RotationalAcceleration MinValue => new RotationalAcceleration(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalAcceleration; + + /// + /// All units of measurement for the RotationalAcceleration quantity. + /// + public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// + public static RotationalAcceleration Zero => new RotationalAcceleration(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalAcceleration.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable RotationalAcceleration from nullable DegreesPerSecondSquared. + /// Get RotationalAcceleration in DegreesPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalAcceleration? FromDegreesPerSecondSquared(QuantityValue? degreespersecondsquared) + public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); + + /// + /// Get RotationalAcceleration in RadiansPerSecondSquared. + /// + public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); + + /// + /// Get RotationalAcceleration in RevolutionsPerMinutePerSecond. + /// + public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalAccelerationUnit unit) { - return degreespersecondsquared.HasValue ? FromDegreesPerSecondSquared(degreespersecondsquared.Value) : default(RotationalAcceleration?); + return GetAbbreviation(unit, null); } /// - /// Get nullable RotationalAcceleration from nullable RadiansPerSecondSquared. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalAcceleration? FromRadiansPerSecondSquared(QuantityValue? radianspersecondsquared) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider) { - return radianspersecondsquared.HasValue ? FromRadiansPerSecondSquared(radianspersecondsquared.Value) : default(RotationalAcceleration?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalAcceleration from DegreesPerSecondSquared. + /// + /// If value is NaN or Infinity. + public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) + { + double value = (double) degreespersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); + } /// - /// Get nullable RotationalAcceleration from nullable RevolutionsPerMinutePerSecond. + /// Get RotationalAcceleration from RadiansPerSecondSquared. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalAcceleration? FromRevolutionsPerMinutePerSecond(QuantityValue? revolutionsperminutepersecond) + /// If value is NaN or Infinity. + public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) { - return revolutionsperminutepersecond.HasValue ? FromRevolutionsPerMinutePerSecond(revolutionsperminutepersecond.Value) : default(RotationalAcceleration?); + double value = (double) radianspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); + } + /// + /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) + { + double value = (double) revolutionsperminutepersecond; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); } /// @@ -95,28 +225,156 @@ public partial struct RotationalAcceleration : IComparable, IComparableValue to convert from. /// Unit to convert from. /// RotationalAcceleration unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalAcceleration? From(QuantityValue? value, RotationalAccelerationUnit fromUnit) + public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) { - return value.HasValue ? new RotationalAcceleration((double)value.Value, fromUnit) : default(RotationalAcceleration?); + return new RotationalAcceleration((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalAcceleration Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalAcceleration result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static RotationalAccelerationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out RotationalAccelerationUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static RotationalAcceleration operator -(RotationalAcceleration right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull #endregion + #region Equality / IComparable + public static bool operator <=(RotationalAcceleration left, RotationalAcceleration right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalAcceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) + public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalAcceleration, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) + public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(RotationalAcceleration other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalAcceleration Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(RotationalAcceleration other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalAccelerationUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromRadiansPerSecondSquared(x.RadiansPerSecondSquared + y.RadiansPerSecondSquared)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalAcceleration result) + /// A hash code for the current RotationalAcceleration. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(RotationalAcceleration); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalAccelerationUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A RotationalAcceleration with the specified unit. + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new RotationalAcceleration(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; + case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(RotationalAccelerationUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == RotationalAccelerationUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalAccelerationUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; + case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs index 66bbf6c9d7..9757bcca37 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,132 +49,314 @@ namespace UnitsNet /// /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct RotationalSpeed : IComparable, IComparable + public partial struct RotationalSpeed : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable RotationalSpeed from nullable CentiradiansPerSecond. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromCentiradiansPerSecond(QuantityValue? centiradianspersecond) + private readonly RotationalSpeedUnit? _unit; + + static RotationalSpeed() { - return centiradianspersecond.HasValue ? FromCentiradiansPerSecond(centiradianspersecond.Value) : default(RotationalSpeed?); + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); } /// - /// Get nullable RotationalSpeed from nullable DeciradiansPerSecond. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromDeciradiansPerSecond(QuantityValue? deciradianspersecond) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public RotationalSpeed(double numericValue, RotationalSpeedUnit unit) { - return deciradianspersecond.HasValue ? FromDeciradiansPerSecond(deciradianspersecond.Value) : default(RotationalSpeed?); + if(unit == RotationalSpeedUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. + /// + public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; + + /// + /// Represents the largest possible value of RotationalSpeed + /// + public static RotationalSpeed MaxValue => new RotationalSpeed(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalSpeed + /// + public static RotationalSpeed MinValue => new RotationalSpeed(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalSpeed; + + /// + /// All units of measurement for the RotationalSpeed quantity. + /// + public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. + /// + public static RotationalSpeed Zero => new RotationalSpeed(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalSpeed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get RotationalSpeed in CentiradiansPerSecond. + /// + public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); + + /// + /// Get RotationalSpeed in DeciradiansPerSecond. + /// + public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); + + /// + /// Get RotationalSpeed in DegreesPerMinute. + /// + public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); + + /// + /// Get RotationalSpeed in DegreesPerSecond. + /// + public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); + + /// + /// Get RotationalSpeed in MicrodegreesPerSecond. + /// + public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); + + /// + /// Get RotationalSpeed in MicroradiansPerSecond. + /// + public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); + + /// + /// Get RotationalSpeed in MillidegreesPerSecond. + /// + public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); + + /// + /// Get RotationalSpeed in MilliradiansPerSecond. + /// + public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); + + /// + /// Get RotationalSpeed in NanodegreesPerSecond. + /// + public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); + + /// + /// Get RotationalSpeed in NanoradiansPerSecond. + /// + public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); + + /// + /// Get RotationalSpeed in RadiansPerSecond. + /// + public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); + /// - /// Get nullable RotationalSpeed from nullable DegreesPerMinute. + /// Get RotationalSpeed in RevolutionsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromDegreesPerMinute(QuantityValue? degreesperminute) + public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); + + /// + /// Get RotationalSpeed in RevolutionsPerSecond. + /// + public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalSpeedUnit unit) { - return degreesperminute.HasValue ? FromDegreesPerMinute(degreesperminute.Value) : default(RotationalSpeed?); + return GetAbbreviation(unit, null); } /// - /// Get nullable RotationalSpeed from nullable DegreesPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromDegreesPerSecond(QuantityValue? degreespersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider) { - return degreespersecond.HasValue ? FromDegreesPerSecond(degreespersecond.Value) : default(RotationalSpeed?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable RotationalSpeed from nullable MicrodegreesPerSecond. + /// Get RotationalSpeed from CentiradiansPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromMicrodegreesPerSecond(QuantityValue? microdegreespersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) { - return microdegreespersecond.HasValue ? FromMicrodegreesPerSecond(microdegreespersecond.Value) : default(RotationalSpeed?); + double value = (double) centiradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); } - /// - /// Get nullable RotationalSpeed from nullable MicroradiansPerSecond. + /// Get RotationalSpeed from DeciradiansPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromMicroradiansPerSecond(QuantityValue? microradianspersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) { - return microradianspersecond.HasValue ? FromMicroradiansPerSecond(microradianspersecond.Value) : default(RotationalSpeed?); + double value = (double) deciradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); } - /// - /// Get nullable RotationalSpeed from nullable MillidegreesPerSecond. + /// Get RotationalSpeed from DegreesPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromMillidegreesPerSecond(QuantityValue? millidegreespersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) { - return millidegreespersecond.HasValue ? FromMillidegreesPerSecond(millidegreespersecond.Value) : default(RotationalSpeed?); + double value = (double) degreesperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); } - /// - /// Get nullable RotationalSpeed from nullable MilliradiansPerSecond. + /// Get RotationalSpeed from DegreesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromMilliradiansPerSecond(QuantityValue? milliradianspersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) { - return milliradianspersecond.HasValue ? FromMilliradiansPerSecond(milliradianspersecond.Value) : default(RotationalSpeed?); + double value = (double) degreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); } - /// - /// Get nullable RotationalSpeed from nullable NanodegreesPerSecond. + /// Get RotationalSpeed from MicrodegreesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromNanodegreesPerSecond(QuantityValue? nanodegreespersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) { - return nanodegreespersecond.HasValue ? FromNanodegreesPerSecond(nanodegreespersecond.Value) : default(RotationalSpeed?); + double value = (double) microdegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); } - /// - /// Get nullable RotationalSpeed from nullable NanoradiansPerSecond. + /// Get RotationalSpeed from MicroradiansPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromNanoradiansPerSecond(QuantityValue? nanoradianspersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) { - return nanoradianspersecond.HasValue ? FromNanoradiansPerSecond(nanoradianspersecond.Value) : default(RotationalSpeed?); + double value = (double) microradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); } - /// - /// Get nullable RotationalSpeed from nullable RadiansPerSecond. + /// Get RotationalSpeed from MillidegreesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromRadiansPerSecond(QuantityValue? radianspersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) { - return radianspersecond.HasValue ? FromRadiansPerSecond(radianspersecond.Value) : default(RotationalSpeed?); + double value = (double) millidegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); } - /// - /// Get nullable RotationalSpeed from nullable RevolutionsPerMinute. + /// Get RotationalSpeed from MilliradiansPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromRevolutionsPerMinute(QuantityValue? revolutionsperminute) + /// If value is NaN or Infinity. + public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) { - return revolutionsperminute.HasValue ? FromRevolutionsPerMinute(revolutionsperminute.Value) : default(RotationalSpeed?); + double value = (double) milliradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); + } + /// + /// Get RotationalSpeed from NanodegreesPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) + { + double value = (double) nanodegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); + } + /// + /// Get RotationalSpeed from NanoradiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) + { + double value = (double) nanoradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); + } + /// + /// Get RotationalSpeed from RadiansPerSecond. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) + { + double value = (double) radianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); + } + /// + /// Get RotationalSpeed from RevolutionsPerMinute. + /// + /// If value is NaN or Infinity. + public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) + { + double value = (double) revolutionsperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); } - /// - /// Get nullable RotationalSpeed from nullable RevolutionsPerSecond. + /// Get RotationalSpeed from RevolutionsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalSpeed? FromRevolutionsPerSecond(QuantityValue? revolutionspersecond) + /// If value is NaN or Infinity. + public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) { - return revolutionspersecond.HasValue ? FromRevolutionsPerSecond(revolutionspersecond.Value) : default(RotationalSpeed?); + double value = (double) revolutionspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); } /// @@ -185,28 +365,156 @@ public partial struct RotationalSpeed : IComparable, IComparableValue to convert from. /// Unit to convert from. /// RotationalSpeed unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalSpeed? From(QuantityValue? value, RotationalSpeedUnit fromUnit) + public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) { - return value.HasValue ? new RotationalSpeed((double)value.Value, fromUnit) : default(RotationalSpeed?); + return new RotationalSpeed((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalSpeed Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalSpeed result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static RotationalSpeedUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out RotationalSpeedUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static RotationalSpeed operator -(RotationalSpeed right) @@ -246,6 +554,8 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] IForm #endregion + #region Equality / IComparable + public static bool operator <=(RotationalSpeed left, RotationalSpeed right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -266,180 +576,240 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] IForm return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalSpeed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(RotationalSpeed left, RotationalSpeed right) + public static bool operator ==(RotationalSpeed left, RotationalSpeed right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalSpeed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(RotationalSpeed left, RotationalSpeed right) + public static bool operator !=(RotationalSpeed left, RotationalSpeed right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(RotationalSpeed other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalSpeed Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(RotationalSpeed other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalSpeedUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromRadiansPerSecond(x.RadiansPerSecond + y.RadiansPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalSpeed result) + /// A hash code for the current RotationalSpeed. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(RotationalSpeed); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalSpeedUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A RotationalSpeed with the specified unit. + public RotationalSpeed ToUnit(RotationalSpeedUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new RotationalSpeed(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(RotationalSpeedUnit unit) + { + if(Unit == unit) + return _value; - if (unit == RotationalSpeedUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalSpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs index ee19c0d991..083edb31ff 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct RotationalStiffness : IComparable, IComparable + public partial struct RotationalStiffness : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessUnit? _unit; + + static RotationalStiffness() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public RotationalStiffness(double numericValue, RotationalStiffnessUnit unit) + { + if(unit == RotationalStiffnessUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. + /// + public static RotationalStiffnessUnit BaseUnit => RotationalStiffnessUnit.NewtonMeterPerRadian; + + /// + /// Represents the largest possible value of RotationalStiffness + /// + public static RotationalStiffness MaxValue => new RotationalStiffness(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalStiffness + /// + public static RotationalStiffness MinValue => new RotationalStiffness(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalStiffness; + + /// + /// All units of measurement for the RotationalStiffness quantity. + /// + public static RotationalStiffnessUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// + public static RotationalStiffness Zero => new RotationalStiffness(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffness.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable RotationalStiffness from nullable KilonewtonMetersPerRadian. + /// Get RotationalStiffness in KilonewtonMetersPerRadian. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffness? FromKilonewtonMetersPerRadian(QuantityValue? kilonewtonmetersperradian) + public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); + + /// + /// Get RotationalStiffness in MeganewtonMetersPerRadian. + /// + public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); + + /// + /// Get RotationalStiffness in NewtonMetersPerRadian. + /// + public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessUnit unit) { - return kilonewtonmetersperradian.HasValue ? FromKilonewtonMetersPerRadian(kilonewtonmetersperradian.Value) : default(RotationalStiffness?); + return GetAbbreviation(unit, null); } /// - /// Get nullable RotationalStiffness from nullable MeganewtonMetersPerRadian. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffness? FromMeganewtonMetersPerRadian(QuantityValue? meganewtonmetersperradian) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider) { - return meganewtonmetersperradian.HasValue ? FromMeganewtonMetersPerRadian(meganewtonmetersperradian.Value) : default(RotationalStiffness?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffness from KilonewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) + { + double value = (double) kilonewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); + } /// - /// Get nullable RotationalStiffness from nullable NewtonMetersPerRadian. + /// Get RotationalStiffness from MeganewtonMetersPerRadian. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffness? FromNewtonMetersPerRadian(QuantityValue? newtonmetersperradian) + /// If value is NaN or Infinity. + public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) { - return newtonmetersperradian.HasValue ? FromNewtonMetersPerRadian(newtonmetersperradian.Value) : default(RotationalStiffness?); + double value = (double) meganewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); + } + /// + /// Get RotationalStiffness from NewtonMetersPerRadian. + /// + /// If value is NaN or Infinity. + public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) + { + double value = (double) newtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); } /// @@ -95,28 +225,156 @@ public partial struct RotationalStiffness : IComparable, IComparableValue to convert from. /// Unit to convert from. /// RotationalStiffness unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffness? From(QuantityValue? value, RotationalStiffnessUnit fromUnit) + public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) { - return value.HasValue ? new RotationalStiffness((double)value.Value, fromUnit) : default(RotationalStiffness?); + return new RotationalStiffness((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalStiffness Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffness result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static RotationalStiffnessUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out RotationalStiffnessUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static RotationalStiffness operator -(RotationalStiffness right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(RotationalStiffness left, RotationalStiffness right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffness, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(RotationalStiffness left, RotationalStiffness right) + public static bool operator ==(RotationalStiffness left, RotationalStiffness right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffness, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(RotationalStiffness left, RotationalStiffness right) + public static bool operator !=(RotationalStiffness left, RotationalStiffness right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(RotationalStiffness other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffness Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(RotationalStiffness other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalStiffnessUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMetersPerRadian(x.NewtonMetersPerRadian + y.NewtonMetersPerRadian)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffness result) + /// A hash code for the current RotationalStiffness. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(RotationalStiffness); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static RotationalStiffnessUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A RotationalStiffness with the specified unit. + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new RotationalStiffness(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; + case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; + case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(RotationalStiffnessUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == RotationalStiffnessUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; + case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; + case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs index 7a077b2878..7c0d807bcc 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,42 +49,174 @@ namespace UnitsNet /// /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct RotationalStiffnessPerLength : IComparable, IComparable + public partial struct RotationalStiffnessPerLength : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalStiffnessPerLengthUnit? _unit; + + static RotationalStiffnessPerLength() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public RotationalStiffnessPerLength(double numericValue, RotationalStiffnessPerLengthUnit unit) + { + if(unit == RotationalStiffnessPerLengthUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. + /// + public static RotationalStiffnessPerLengthUnit BaseUnit => RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + + /// + /// Represents the largest possible value of RotationalStiffnessPerLength + /// + public static RotationalStiffnessPerLength MaxValue => new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of RotationalStiffnessPerLength + /// + public static RotationalStiffnessPerLength MinValue => new RotationalStiffnessPerLength(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.RotationalStiffnessPerLength; + + /// + /// All units of measurement for the RotationalStiffnessPerLength quantity. + /// + public static RotationalStiffnessPerLengthUnit[] Units { get; } = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// + public static RotationalStiffnessPerLength Zero => new RotationalStiffnessPerLength(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => RotationalStiffnessPerLength.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable RotationalStiffnessPerLength from nullable KilonewtonMetersPerRadianPerMeter. + /// Get RotationalStiffnessPerLength in KilonewtonMetersPerRadianPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffnessPerLength? FromKilonewtonMetersPerRadianPerMeter(QuantityValue? kilonewtonmetersperradianpermeter) + public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + + /// + /// Get RotationalStiffnessPerLength in MeganewtonMetersPerRadianPerMeter. + /// + public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + + /// + /// Get RotationalStiffnessPerLength in NewtonMetersPerRadianPerMeter. + /// + public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) { - return kilonewtonmetersperradianpermeter.HasValue ? FromKilonewtonMetersPerRadianPerMeter(kilonewtonmetersperradianpermeter.Value) : default(RotationalStiffnessPerLength?); + return GetAbbreviation(unit, null); } /// - /// Get nullable RotationalStiffnessPerLength from nullable MeganewtonMetersPerRadianPerMeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffnessPerLength? FromMeganewtonMetersPerRadianPerMeter(QuantityValue? meganewtonmetersperradianpermeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider) { - return meganewtonmetersperradianpermeter.HasValue ? FromMeganewtonMetersPerRadianPerMeter(meganewtonmetersperradianpermeter.Value) : default(RotationalStiffnessPerLength?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get RotationalStiffnessPerLength from KilonewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) + { + double value = (double) kilonewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + } /// - /// Get nullable RotationalStiffnessPerLength from nullable NewtonMetersPerRadianPerMeter. + /// Get RotationalStiffnessPerLength from MeganewtonMetersPerRadianPerMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static RotationalStiffnessPerLength? FromNewtonMetersPerRadianPerMeter(QuantityValue? newtonmetersperradianpermeter) + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) { - return newtonmetersperradianpermeter.HasValue ? FromNewtonMetersPerRadianPerMeter(newtonmetersperradianpermeter.Value) : default(RotationalStiffnessPerLength?); + double value = (double) meganewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + } + /// + /// Get RotationalStiffnessPerLength from NewtonMetersPerRadianPerMeter. + /// + /// If value is NaN or Infinity. + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) + { + double value = (double) newtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); } /// @@ -95,28 +225,156 @@ public partial struct RotationalStiffnessPerLength : IComparable, IComparableValue to convert from. /// Unit to convert from. /// RotationalStiffnessPerLength unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static RotationalStiffnessPerLength? From(QuantityValue? value, RotationalStiffnessPerLengthUnit fromUnit) + public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) { - return value.HasValue ? new RotationalStiffnessPerLength((double)value.Value, fromUnit) : default(RotationalStiffnessPerLength?); + return new RotationalStiffnessPerLength((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalStiffnessPerLength Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffnessPerLength result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static RotationalStiffnessPerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out RotationalStiffnessPerLengthUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength right) @@ -156,6 +414,8 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [Can #endregion + #region Equality / IComparable + public static bool operator <=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -176,180 +436,220 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [Can return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffnessPerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(RotationalStiffnessPerLength, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(RotationalStiffnessPerLength other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffnessPerLength Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(RotationalStiffnessPerLength other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - RotationalStiffnessPerLengthUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMetersPerRadianPerMeter(x.NewtonMetersPerRadianPerMeter + y.NewtonMetersPerRadianPerMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out RotationalStiffnessPerLength result) + /// A hash code for the current RotationalStiffnessPerLength. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(RotationalStiffnessPerLength); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessPerLengthUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static RotationalStiffnessPerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A RotationalStiffnessPerLength with the specified unit. + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new RotationalStiffnessPerLength(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; + case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; + case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(RotationalStiffnessPerLengthUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == RotationalStiffnessPerLengthUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalStiffnessPerLengthUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; + case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; + case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(RotationalStiffnessPerLengthUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs index ec8a1c28c7..d8f03d8b08 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,149 @@ namespace UnitsNet /// /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct SolidAngle : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Solid_angle + /// + public partial struct SolidAngle : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SolidAngleUnit? _unit; + + static SolidAngle() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public SolidAngle(double numericValue, SolidAngleUnit unit) + { + if(unit == SolidAngleUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. + /// + public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; + + /// + /// Represents the largest possible value of SolidAngle + /// + public static SolidAngle MaxValue => new SolidAngle(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SolidAngle + /// + public static SolidAngle MinValue => new SolidAngle(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SolidAngle; + + /// + /// All units of measurement for the SolidAngle quantity. + /// + public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. + /// + public static SolidAngle Zero => new SolidAngle(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SolidAngle.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SolidAngle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SolidAngle in Steradians. + /// + public double Steradians => As(SolidAngleUnit.Steradian); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SolidAngleUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable SolidAngle from nullable Steradians. + /// Get SolidAngle from Steradians. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SolidAngle? FromSteradians(QuantityValue? steradians) + /// If value is NaN or Infinity. + public static SolidAngle FromSteradians(QuantityValue steradians) { - return steradians.HasValue ? FromSteradians(steradians.Value) : default(SolidAngle?); + double value = (double) steradians; + return new SolidAngle(value, SolidAngleUnit.Steradian); } /// @@ -77,28 +200,156 @@ public partial struct SolidAngle : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// SolidAngle unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SolidAngle? From(QuantityValue? value, SolidAngleUnit fromUnit) + public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) { - return value.HasValue ? new SolidAngle((double)value.Value, fromUnit) : default(SolidAngle?); + return new SolidAngle((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static SolidAngle Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SolidAngle result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SolidAngle result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SolidAngleUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SolidAngleUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SolidAngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SolidAngleUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static SolidAngle operator -(SolidAngle right) @@ -138,6 +389,8 @@ public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] IFormatPro #endregion + #region Equality / IComparable + public static bool operator <=(SolidAngle left, SolidAngle right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +411,216 @@ public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] IFormatPro return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SolidAngle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(SolidAngle left, SolidAngle right) + public static bool operator ==(SolidAngle left, SolidAngle right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SolidAngle, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(SolidAngle left, SolidAngle right) + public static bool operator !=(SolidAngle left, SolidAngle right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(SolidAngle other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SolidAngle Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(SolidAngle other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SolidAngleUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSteradians(x.Steradians + y.Steradians)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SolidAngle result) + /// A hash code for the current SolidAngle. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(SolidAngle); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SolidAngleUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this SolidAngle to another SolidAngle with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A SolidAngle with the specified unit. + public SolidAngle ToUnit(SolidAngleUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new SolidAngle(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SolidAngleUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SolidAngleUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SolidAngleUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SolidAngleUnit.Steradian: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs index 083b1ed18a..d72c3d329b 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,247 @@ namespace UnitsNet /// /// The SpecificEnergy /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct SpecificEnergy : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Specific_energy + /// + public partial struct SpecificEnergy : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable SpecificEnergy from nullable CaloriesPerGram. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromCaloriesPerGram(QuantityValue? caloriespergram) + private readonly SpecificEnergyUnit? _unit; + + static SpecificEnergy() { - return caloriespergram.HasValue ? FromCaloriesPerGram(caloriespergram.Value) : default(SpecificEnergy?); + BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); } /// - /// Get nullable SpecificEnergy from nullable JoulesPerKilogram. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromJoulesPerKilogram(QuantityValue? joulesperkilogram) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public SpecificEnergy(double numericValue, SpecificEnergyUnit unit) { - return joulesperkilogram.HasValue ? FromJoulesPerKilogram(joulesperkilogram.Value) : default(SpecificEnergy?); + if(unit == SpecificEnergyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. + /// + public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; + + /// + /// Represents the largest possible value of SpecificEnergy + /// + public static SpecificEnergy MaxValue => new SpecificEnergy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificEnergy + /// + public static SpecificEnergy MinValue => new SpecificEnergy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificEnergy; + + /// + /// All units of measurement for the SpecificEnergy quantity. + /// + public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. + /// + public static SpecificEnergy Zero => new SpecificEnergy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable SpecificEnergy from nullable KilocaloriesPerGram. + /// The of this quantity. + /// + public QuantityType Type => SpecificEnergy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificEnergy in CaloriesPerGram. + /// + public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); + + /// + /// Get SpecificEnergy in JoulesPerKilogram. + /// + public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); + + /// + /// Get SpecificEnergy in KilocaloriesPerGram. + /// + public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); + + /// + /// Get SpecificEnergy in KilojoulesPerKilogram. + /// + public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); + + /// + /// Get SpecificEnergy in KilowattHoursPerKilogram. + /// + public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); + + /// + /// Get SpecificEnergy in MegajoulesPerKilogram. + /// + public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); + + /// + /// Get SpecificEnergy in MegawattHoursPerKilogram. + /// + public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); + + /// + /// Get SpecificEnergy in WattHoursPerKilogram. + /// + public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromKilocaloriesPerGram(QuantityValue? kilocaloriespergram) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEnergyUnit unit) { - return kilocaloriespergram.HasValue ? FromKilocaloriesPerGram(kilocaloriespergram.Value) : default(SpecificEnergy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable SpecificEnergy from nullable KilojoulesPerKilogram. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromKilojoulesPerKilogram(QuantityValue? kilojoulesperkilogram) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider) { - return kilojoulesperkilogram.HasValue ? FromKilojoulesPerKilogram(kilojoulesperkilogram.Value) : default(SpecificEnergy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable SpecificEnergy from nullable KilowattHoursPerKilogram. + /// Get SpecificEnergy from CaloriesPerGram. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromKilowattHoursPerKilogram(QuantityValue? kilowatthoursperkilogram) + /// If value is NaN or Infinity. + public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) { - return kilowatthoursperkilogram.HasValue ? FromKilowattHoursPerKilogram(kilowatthoursperkilogram.Value) : default(SpecificEnergy?); + double value = (double) caloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); } - /// - /// Get nullable SpecificEnergy from nullable MegajoulesPerKilogram. + /// Get SpecificEnergy from JoulesPerKilogram. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromMegajoulesPerKilogram(QuantityValue? megajoulesperkilogram) + /// If value is NaN or Infinity. + public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) { - return megajoulesperkilogram.HasValue ? FromMegajoulesPerKilogram(megajoulesperkilogram.Value) : default(SpecificEnergy?); + double value = (double) joulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); } - /// - /// Get nullable SpecificEnergy from nullable MegawattHoursPerKilogram. + /// Get SpecificEnergy from KilocaloriesPerGram. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromMegawattHoursPerKilogram(QuantityValue? megawatthoursperkilogram) + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) { - return megawatthoursperkilogram.HasValue ? FromMegawattHoursPerKilogram(megawatthoursperkilogram.Value) : default(SpecificEnergy?); + double value = (double) kilocaloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); + } + /// + /// Get SpecificEnergy from KilojoulesPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) + { + double value = (double) kilojoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); + } + /// + /// Get SpecificEnergy from KilowattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) + { + double value = (double) kilowatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); + } + /// + /// Get SpecificEnergy from MegajoulesPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) + { + double value = (double) megajoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); } - /// - /// Get nullable SpecificEnergy from nullable WattHoursPerKilogram. + /// Get SpecificEnergy from MegawattHoursPerKilogram. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEnergy? FromWattHoursPerKilogram(QuantityValue? watthoursperkilogram) + /// If value is NaN or Infinity. + public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) { - return watthoursperkilogram.HasValue ? FromWattHoursPerKilogram(watthoursperkilogram.Value) : default(SpecificEnergy?); + double value = (double) megawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); + } + /// + /// Get SpecificEnergy from WattHoursPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) + { + double value = (double) watthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); } /// @@ -140,28 +298,156 @@ public partial struct SpecificEnergy : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// SpecificEnergy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEnergy? From(QuantityValue? value, SpecificEnergyUnit fromUnit) + public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) { - return value.HasValue ? new SpecificEnergy((double)value.Value, fromUnit) : default(SpecificEnergy?); + return new SpecificEnergy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEnergy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SpecificEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SpecificEnergyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static SpecificEnergy operator -(SpecificEnergy right) @@ -201,6 +487,8 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(SpecificEnergy left, SpecificEnergy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +509,230 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(SpecificEnergy left, SpecificEnergy right) + public static bool operator ==(SpecificEnergy left, SpecificEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEnergy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(SpecificEnergy left, SpecificEnergy right) + public static bool operator !=(SpecificEnergy left, SpecificEnergy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(SpecificEnergy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEnergy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(SpecificEnergy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificEnergyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKilogram(x.JoulesPerKilogram + y.JoulesPerKilogram)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEnergy result) + /// A hash code for the current SpecificEnergy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(SpecificEnergy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEnergyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A SpecificEnergy with the specified unit. + public SpecificEnergy ToUnit(SpecificEnergyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new SpecificEnergy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEnergyUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return _value; + case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(SpecificEnergyUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SpecificEnergyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEnergyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; + case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs index 58a83d2139..b91712cb2e 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,87 +49,244 @@ namespace UnitsNet /// /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct SpecificEntropy : IComparable, IComparable + public partial struct SpecificEntropy : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable SpecificEntropy from nullable CaloriesPerGramKelvin. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromCaloriesPerGramKelvin(QuantityValue? caloriespergramkelvin) + private readonly SpecificEntropyUnit? _unit; + + static SpecificEntropy() { - return caloriespergramkelvin.HasValue ? FromCaloriesPerGramKelvin(caloriespergramkelvin.Value) : default(SpecificEntropy?); + BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); } /// - /// Get nullable SpecificEntropy from nullable JoulesPerKilogramDegreeCelsius. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromJoulesPerKilogramDegreeCelsius(QuantityValue? joulesperkilogramdegreecelsius) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public SpecificEntropy(double numericValue, SpecificEntropyUnit unit) { - return joulesperkilogramdegreecelsius.HasValue ? FromJoulesPerKilogramDegreeCelsius(joulesperkilogramdegreecelsius.Value) : default(SpecificEntropy?); + if(unit == SpecificEntropyUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. + /// + public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; + + /// + /// Represents the largest possible value of SpecificEntropy + /// + public static SpecificEntropy MaxValue => new SpecificEntropy(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificEntropy + /// + public static SpecificEntropy MinValue => new SpecificEntropy(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificEntropy; + + /// + /// All units of measurement for the SpecificEntropy quantity. + /// + public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// + public static SpecificEntropy Zero => new SpecificEntropy(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + /// - /// Get nullable SpecificEntropy from nullable JoulesPerKilogramKelvin. + /// The of this quantity. + /// + public QuantityType Type => SpecificEntropy.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificEntropy in CaloriesPerGramKelvin. + /// + public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); + + /// + /// Get SpecificEntropy in JoulesPerKilogramDegreeCelsius. + /// + public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in JoulesPerKilogramKelvin. + /// + public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); + + /// + /// Get SpecificEntropy in KilocaloriesPerGramKelvin. + /// + public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); + + /// + /// Get SpecificEntropy in KilojoulesPerKilogramDegreeCelsius. + /// + public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in KilojoulesPerKilogramKelvin. + /// + public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); + + /// + /// Get SpecificEntropy in MegajoulesPerKilogramDegreeCelsius. + /// + public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + + /// + /// Get SpecificEntropy in MegajoulesPerKilogramKelvin. + /// + public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromJoulesPerKilogramKelvin(QuantityValue? joulesperkilogramkelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificEntropyUnit unit) { - return joulesperkilogramkelvin.HasValue ? FromJoulesPerKilogramKelvin(joulesperkilogramkelvin.Value) : default(SpecificEntropy?); + return GetAbbreviation(unit, null); } /// - /// Get nullable SpecificEntropy from nullable KilocaloriesPerGramKelvin. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromKilocaloriesPerGramKelvin(QuantityValue? kilocaloriespergramkelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider) { - return kilocaloriespergramkelvin.HasValue ? FromKilocaloriesPerGramKelvin(kilocaloriespergramkelvin.Value) : default(SpecificEntropy?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable SpecificEntropy from nullable KilojoulesPerKilogramDegreeCelsius. + /// Get SpecificEntropy from CaloriesPerGramKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromKilojoulesPerKilogramDegreeCelsius(QuantityValue? kilojoulesperkilogramdegreecelsius) + /// If value is NaN or Infinity. + public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) { - return kilojoulesperkilogramdegreecelsius.HasValue ? FromKilojoulesPerKilogramDegreeCelsius(kilojoulesperkilogramdegreecelsius.Value) : default(SpecificEntropy?); + double value = (double) caloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); } - /// - /// Get nullable SpecificEntropy from nullable KilojoulesPerKilogramKelvin. + /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromKilojoulesPerKilogramKelvin(QuantityValue? kilojoulesperkilogramkelvin) + /// If value is NaN or Infinity. + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) { - return kilojoulesperkilogramkelvin.HasValue ? FromKilojoulesPerKilogramKelvin(kilojoulesperkilogramkelvin.Value) : default(SpecificEntropy?); + double value = (double) joulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); } - /// - /// Get nullable SpecificEntropy from nullable MegajoulesPerKilogramDegreeCelsius. + /// Get SpecificEntropy from JoulesPerKilogramKelvin. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromMegajoulesPerKilogramDegreeCelsius(QuantityValue? megajoulesperkilogramdegreecelsius) + /// If value is NaN or Infinity. + public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) { - return megajoulesperkilogramdegreecelsius.HasValue ? FromMegajoulesPerKilogramDegreeCelsius(megajoulesperkilogramdegreecelsius.Value) : default(SpecificEntropy?); + double value = (double) joulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); + } + /// + /// Get SpecificEntropy from KilocaloriesPerGramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) + { + double value = (double) kilocaloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) + { + double value = (double) kilojoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) + { + double value = (double) kilojoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); } - /// - /// Get nullable SpecificEntropy from nullable MegajoulesPerKilogramKelvin. + /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificEntropy? FromMegajoulesPerKilogramKelvin(QuantityValue? megajoulesperkilogramkelvin) + /// If value is NaN or Infinity. + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) { - return megajoulesperkilogramkelvin.HasValue ? FromMegajoulesPerKilogramKelvin(megajoulesperkilogramkelvin.Value) : default(SpecificEntropy?); + double value = (double) megajoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + } + /// + /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. + /// + /// If value is NaN or Infinity. + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) + { + double value = (double) megajoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); } /// @@ -140,28 +295,156 @@ public partial struct SpecificEntropy : IComparable, IComparableValue to convert from. /// Unit to convert from. /// SpecificEntropy unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificEntropy? From(QuantityValue? value, SpecificEntropyUnit fromUnit) + public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) { - return value.HasValue ? new SpecificEntropy((double)value.Value, fromUnit) : default(SpecificEntropy?); + return new SpecificEntropy((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEntropy result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SpecificEntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SpecificEntropyUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static SpecificEntropy operator -(SpecificEntropy right) @@ -201,6 +484,8 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] IForm #endregion + #region Equality / IComparable + public static bool operator <=(SpecificEntropy left, SpecificEntropy right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -221,180 +506,230 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] IForm return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(SpecificEntropy left, SpecificEntropy right) + public static bool operator ==(SpecificEntropy left, SpecificEntropy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificEntropy, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(SpecificEntropy left, SpecificEntropy right) + public static bool operator !=(SpecificEntropy left, SpecificEntropy right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(SpecificEntropy other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEntropy Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(SpecificEntropy other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificEntropyUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromJoulesPerKilogramKelvin(x.JoulesPerKilogramKelvin + y.JoulesPerKilogramKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificEntropy result) + /// A hash code for the current SpecificEntropy. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(SpecificEntropy); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEntropyUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A SpecificEntropy with the specified unit. + public SpecificEntropy ToUnit(SpecificEntropyUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new SpecificEntropy(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEntropyUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case SpecificEntropyUnit.CaloriePerGramKelvin: return _value*4.184e3; + case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; + case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; + case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value*4.184e3) * 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; + case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; + case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(SpecificEntropyUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SpecificEntropyUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEntropyUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs index 3c77890eac..04e161eb6a 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,160 @@ namespace UnitsNet /// /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct SpecificVolume : IComparable, IComparable + public partial struct SpecificVolume : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificVolumeUnit? _unit; + + static SpecificVolume() + { + BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public SpecificVolume(double numericValue, SpecificVolumeUnit unit) + { + if(unit == SpecificVolumeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. + /// + public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; + + /// + /// Represents the largest possible value of SpecificVolume + /// + public static SpecificVolume MaxValue => new SpecificVolume(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificVolume + /// + public static SpecificVolume MinValue => new SpecificVolume(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificVolume; + + /// + /// All units of measurement for the SpecificVolume quantity. + /// + public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// + public static SpecificVolume Zero => new SpecificVolume(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificVolume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable SpecificVolume from nullable CubicFeetPerPound. + /// Get SpecificVolume in CubicFeetPerPound. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificVolume? FromCubicFeetPerPound(QuantityValue? cubicfeetperpound) + public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + + /// + /// Get SpecificVolume in CubicMetersPerKilogram. + /// + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificVolumeUnit unit) { - return cubicfeetperpound.HasValue ? FromCubicFeetPerPound(cubicfeetperpound.Value) : default(SpecificVolume?); + return GetAbbreviation(unit, null); } /// - /// Get nullable SpecificVolume from nullable CubicMetersPerKilogram. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificVolume? FromCubicMetersPerKilogram(QuantityValue? cubicmetersperkilogram) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider) { - return cubicmetersperkilogram.HasValue ? FromCubicMetersPerKilogram(cubicmetersperkilogram.Value) : default(SpecificVolume?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get SpecificVolume from CubicFeetPerPound. + /// + /// If value is NaN or Infinity. + public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) + { + double value = (double) cubicfeetperpound; + return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); + } + /// + /// Get SpecificVolume from CubicMetersPerKilogram. + /// + /// If value is NaN or Infinity. + public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) + { + double value = (double) cubicmetersperkilogram; + return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); } /// @@ -86,28 +211,156 @@ public partial struct SpecificVolume : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// SpecificVolume unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificVolume? From(QuantityValue? value, SpecificVolumeUnit fromUnit) + public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) { - return value.HasValue ? new SpecificVolume((double)value.Value, fromUnit) : default(SpecificVolume?); + return new SpecificVolume((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificVolume Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificVolume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificVolume result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SpecificVolumeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificVolumeUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SpecificVolumeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static SpecificVolume operator -(SpecificVolume right) @@ -147,6 +400,8 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(SpecificVolume left, SpecificVolume right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -167,180 +422,218 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificVolume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(SpecificVolume left, SpecificVolume right) + public static bool operator ==(SpecificVolume left, SpecificVolume right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificVolume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(SpecificVolume left, SpecificVolume right) + public static bool operator !=(SpecificVolume left, SpecificVolume right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(SpecificVolume other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificVolume Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(SpecificVolume other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificVolumeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerKilogram(x.CubicMetersPerKilogram + y.CubicMetersPerKilogram)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificVolume result) + /// A hash code for the current SpecificVolume. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(SpecificVolume); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificVolumeUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this SpecificVolume to another SpecificVolume with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A SpecificVolume with the specified unit. + public SpecificVolume ToUnit(SpecificVolumeUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new SpecificVolume(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificVolumeUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case SpecificVolumeUnit.CubicFootPerPound: return _value/16.01846353; + case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(SpecificVolumeUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SpecificVolumeUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificVolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue*16.01846353; + case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs index 7a778167e6..ce31c9bb27 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,168 +49,373 @@ namespace UnitsNet /// /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct SpecificWeight : IComparable, IComparable + /// + /// http://en.wikipedia.org/wiki/Specificweight + /// + public partial struct SpecificWeight : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable SpecificWeight from nullable KilogramsForcePerCubicCentimeter. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilogramsForcePerCubicCentimeter(QuantityValue? kilogramsforcepercubiccentimeter) + private readonly SpecificWeightUnit? _unit; + + static SpecificWeight() { - return kilogramsforcepercubiccentimeter.HasValue ? FromKilogramsForcePerCubicCentimeter(kilogramsforcepercubiccentimeter.Value) : default(SpecificWeight?); + BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable SpecificWeight from nullable KilogramsForcePerCubicMeter. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilogramsForcePerCubicMeter(QuantityValue? kilogramsforcepercubicmeter) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public SpecificWeight(double numericValue, SpecificWeightUnit unit) { - return kilogramsforcepercubicmeter.HasValue ? FromKilogramsForcePerCubicMeter(kilogramsforcepercubicmeter.Value) : default(SpecificWeight?); + if(unit == SpecificWeightUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. + /// + public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; + + /// + /// Represents the largest possible value of SpecificWeight + /// + public static SpecificWeight MaxValue => new SpecificWeight(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of SpecificWeight + /// + public static SpecificWeight MinValue => new SpecificWeight(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.SpecificWeight; + + /// + /// All units of measurement for the SpecificWeight quantity. + /// + public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// + public static SpecificWeight Zero => new SpecificWeight(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => SpecificWeight.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get SpecificWeight in KilogramsForcePerCubicCentimeter. + /// + public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); + + /// + /// Get SpecificWeight in KilogramsForcePerCubicMeter. + /// + public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); + + /// + /// Get SpecificWeight in KilogramsForcePerCubicMillimeter. + /// + public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicCentimeter. + /// + public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicMeter. + /// + public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); + + /// + /// Get SpecificWeight in KilonewtonsPerCubicMillimeter. + /// + public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); + + /// + /// Get SpecificWeight in KilopoundsForcePerCubicFoot. + /// + public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); + + /// + /// Get SpecificWeight in KilopoundsForcePerCubicInch. + /// + public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); + + /// + /// Get SpecificWeight in MeganewtonsPerCubicMeter. + /// + public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicCentimeter. + /// + public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicMeter. + /// + public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); + + /// + /// Get SpecificWeight in NewtonsPerCubicMillimeter. + /// + public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); + + /// + /// Get SpecificWeight in PoundsForcePerCubicFoot. + /// + public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); + + /// + /// Get SpecificWeight in PoundsForcePerCubicInch. + /// + public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); + + /// + /// Get SpecificWeight in TonnesForcePerCubicCentimeter. + /// + public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); + + /// + /// Get SpecificWeight in TonnesForcePerCubicMeter. + /// + public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); + /// - /// Get nullable SpecificWeight from nullable KilogramsForcePerCubicMillimeter. + /// Get SpecificWeight in TonnesForcePerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilogramsForcePerCubicMillimeter(QuantityValue? kilogramsforcepercubicmillimeter) + public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpecificWeightUnit unit) { - return kilogramsforcepercubicmillimeter.HasValue ? FromKilogramsForcePerCubicMillimeter(kilogramsforcepercubicmillimeter.Value) : default(SpecificWeight?); + return GetAbbreviation(unit, null); } /// - /// Get nullable SpecificWeight from nullable KilonewtonsPerCubicCentimeter. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilonewtonsPerCubicCentimeter(QuantityValue? kilonewtonspercubiccentimeter) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider) { - return kilonewtonspercubiccentimeter.HasValue ? FromKilonewtonsPerCubicCentimeter(kilonewtonspercubiccentimeter.Value) : default(SpecificWeight?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable SpecificWeight from nullable KilonewtonsPerCubicMeter. + /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilonewtonsPerCubicMeter(QuantityValue? kilonewtonspercubicmeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) { - return kilonewtonspercubicmeter.HasValue ? FromKilonewtonsPerCubicMeter(kilonewtonspercubicmeter.Value) : default(SpecificWeight?); + double value = (double) kilogramsforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); } - /// - /// Get nullable SpecificWeight from nullable KilonewtonsPerCubicMillimeter. + /// Get SpecificWeight from KilogramsForcePerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilonewtonsPerCubicMillimeter(QuantityValue? kilonewtonspercubicmillimeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) { - return kilonewtonspercubicmillimeter.HasValue ? FromKilonewtonsPerCubicMillimeter(kilonewtonspercubicmillimeter.Value) : default(SpecificWeight?); + double value = (double) kilogramsforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); } - /// - /// Get nullable SpecificWeight from nullable KilopoundsForcePerCubicFoot. + /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilopoundsForcePerCubicFoot(QuantityValue? kilopoundsforcepercubicfoot) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) { - return kilopoundsforcepercubicfoot.HasValue ? FromKilopoundsForcePerCubicFoot(kilopoundsforcepercubicfoot.Value) : default(SpecificWeight?); + double value = (double) kilogramsforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); } - /// - /// Get nullable SpecificWeight from nullable KilopoundsForcePerCubicInch. + /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromKilopoundsForcePerCubicInch(QuantityValue? kilopoundsforcepercubicinch) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) { - return kilopoundsforcepercubicinch.HasValue ? FromKilopoundsForcePerCubicInch(kilopoundsforcepercubicinch.Value) : default(SpecificWeight?); + double value = (double) kilonewtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); } - /// - /// Get nullable SpecificWeight from nullable MeganewtonsPerCubicMeter. + /// Get SpecificWeight from KilonewtonsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromMeganewtonsPerCubicMeter(QuantityValue? meganewtonspercubicmeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) { - return meganewtonspercubicmeter.HasValue ? FromMeganewtonsPerCubicMeter(meganewtonspercubicmeter.Value) : default(SpecificWeight?); + double value = (double) kilonewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); } - /// - /// Get nullable SpecificWeight from nullable NewtonsPerCubicCentimeter. + /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromNewtonsPerCubicCentimeter(QuantityValue? newtonspercubiccentimeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) { - return newtonspercubiccentimeter.HasValue ? FromNewtonsPerCubicCentimeter(newtonspercubiccentimeter.Value) : default(SpecificWeight?); + double value = (double) kilonewtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); } - /// - /// Get nullable SpecificWeight from nullable NewtonsPerCubicMeter. + /// Get SpecificWeight from KilopoundsForcePerCubicFoot. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromNewtonsPerCubicMeter(QuantityValue? newtonspercubicmeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) { - return newtonspercubicmeter.HasValue ? FromNewtonsPerCubicMeter(newtonspercubicmeter.Value) : default(SpecificWeight?); + double value = (double) kilopoundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); } - /// - /// Get nullable SpecificWeight from nullable NewtonsPerCubicMillimeter. + /// Get SpecificWeight from KilopoundsForcePerCubicInch. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromNewtonsPerCubicMillimeter(QuantityValue? newtonspercubicmillimeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) { - return newtonspercubicmillimeter.HasValue ? FromNewtonsPerCubicMillimeter(newtonspercubicmillimeter.Value) : default(SpecificWeight?); + double value = (double) kilopoundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); } - /// - /// Get nullable SpecificWeight from nullable PoundsForcePerCubicFoot. + /// Get SpecificWeight from MeganewtonsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromPoundsForcePerCubicFoot(QuantityValue? poundsforcepercubicfoot) + /// If value is NaN or Infinity. + public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) { - return poundsforcepercubicfoot.HasValue ? FromPoundsForcePerCubicFoot(poundsforcepercubicfoot.Value) : default(SpecificWeight?); + double value = (double) meganewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); } - /// - /// Get nullable SpecificWeight from nullable PoundsForcePerCubicInch. + /// Get SpecificWeight from NewtonsPerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromPoundsForcePerCubicInch(QuantityValue? poundsforcepercubicinch) + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) { - return poundsforcepercubicinch.HasValue ? FromPoundsForcePerCubicInch(poundsforcepercubicinch.Value) : default(SpecificWeight?); + double value = (double) newtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); } - /// - /// Get nullable SpecificWeight from nullable TonnesForcePerCubicCentimeter. + /// Get SpecificWeight from NewtonsPerCubicMeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromTonnesForcePerCubicCentimeter(QuantityValue? tonnesforcepercubiccentimeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) { - return tonnesforcepercubiccentimeter.HasValue ? FromTonnesForcePerCubicCentimeter(tonnesforcepercubiccentimeter.Value) : default(SpecificWeight?); + double value = (double) newtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); } - /// - /// Get nullable SpecificWeight from nullable TonnesForcePerCubicMeter. + /// Get SpecificWeight from NewtonsPerCubicMillimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromTonnesForcePerCubicMeter(QuantityValue? tonnesforcepercubicmeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) { - return tonnesforcepercubicmeter.HasValue ? FromTonnesForcePerCubicMeter(tonnesforcepercubicmeter.Value) : default(SpecificWeight?); + double value = (double) newtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicFoot. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) + { + double value = (double) poundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); + } + /// + /// Get SpecificWeight from PoundsForcePerCubicInch. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) + { + double value = (double) poundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); } - /// - /// Get nullable SpecificWeight from nullable TonnesForcePerCubicMillimeter. + /// Get SpecificWeight from TonnesForcePerCubicCentimeter. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static SpecificWeight? FromTonnesForcePerCubicMillimeter(QuantityValue? tonnesforcepercubicmillimeter) + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) { - return tonnesforcepercubicmillimeter.HasValue ? FromTonnesForcePerCubicMillimeter(tonnesforcepercubicmillimeter.Value) : default(SpecificWeight?); + double value = (double) tonnesforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) + { + double value = (double) tonnesforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); + } + /// + /// Get SpecificWeight from TonnesForcePerCubicMillimeter. + /// + /// If value is NaN or Infinity. + public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) + { + double value = (double) tonnesforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); } /// @@ -221,28 +424,156 @@ public partial struct SpecificWeight : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// SpecificWeight unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static SpecificWeight? From(QuantityValue? value, SpecificWeightUnit fromUnit) + public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) { - return value.HasValue ? new SpecificWeight((double)value.Value, fromUnit) : default(SpecificWeight?); + return new SpecificWeight((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificWeight Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out SpecificWeight result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificWeight result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SpecificWeightUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SpecificWeightUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); } + public static bool TryParseUnit(string str, out SpecificWeightUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SpecificWeightUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static SpecificWeight operator -(SpecificWeight right) @@ -282,6 +613,8 @@ public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] IForma #endregion + #region Equality / IComparable + public static bool operator <=(SpecificWeight left, SpecificWeight right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -302,180 +635,248 @@ public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] IForma return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificWeight, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(SpecificWeight left, SpecificWeight right) + public static bool operator ==(SpecificWeight left, SpecificWeight right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(SpecificWeight, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(SpecificWeight left, SpecificWeight right) + public static bool operator !=(SpecificWeight left, SpecificWeight right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(SpecificWeight other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificWeight Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(SpecificWeight other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpecificWeightUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonsPerCubicMeter(x.NewtonsPerCubicMeter + y.NewtonsPerCubicMeter)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out SpecificWeight result) + /// A hash code for the current SpecificWeight. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(SpecificWeight); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificWeightUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this SpecificWeight to another SpecificWeight with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A SpecificWeight with the specified unit. + public SpecificWeight ToUnit(SpecificWeightUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new SpecificWeight(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificWeightUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SpecificWeightUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificWeightUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs index b88736a5c0..a557138fe8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,303 +49,580 @@ namespace UnitsNet /// /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Speed : IComparable, IComparable + public partial struct Speed : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Speed from nullable CentimetersPerHour. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromCentimetersPerHour(QuantityValue? centimetersperhour) + private readonly SpeedUnit? _unit; + + static Speed() { - return centimetersperhour.HasValue ? FromCentimetersPerHour(centimetersperhour.Value) : default(Speed?); + BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); } /// - /// Get nullable Speed from nullable CentimetersPerMinutes. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromCentimetersPerMinutes(QuantityValue? centimetersperminutes) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Speed(double numericValue, SpeedUnit unit) { - return centimetersperminutes.HasValue ? FromCentimetersPerMinutes(centimetersperminutes.Value) : default(Speed?); + if(unit == SpeedUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. + /// + public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; + + /// + /// Represents the largest possible value of Speed + /// + public static Speed MaxValue => new Speed(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Speed + /// + public static Speed MinValue => new Speed(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Speed; + + /// + /// All units of measurement for the Speed quantity. + /// + public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. + /// + public static Speed Zero => new Speed(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Speed.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Speed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Speed in CentimetersPerHour. + /// + public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); + + /// + /// Get Speed in CentimetersPerMinutes. + /// + public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); + + /// + /// Get Speed in CentimetersPerSecond. + /// + public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); + + /// + /// Get Speed in DecimetersPerMinutes. + /// + public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); + + /// + /// Get Speed in DecimetersPerSecond. + /// + public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); + + /// + /// Get Speed in FeetPerHour. + /// + public double FeetPerHour => As(SpeedUnit.FootPerHour); + + /// + /// Get Speed in FeetPerMinute. + /// + public double FeetPerMinute => As(SpeedUnit.FootPerMinute); + + /// + /// Get Speed in FeetPerSecond. + /// + public double FeetPerSecond => As(SpeedUnit.FootPerSecond); + + /// + /// Get Speed in InchesPerHour. + /// + public double InchesPerHour => As(SpeedUnit.InchPerHour); + + /// + /// Get Speed in InchesPerMinute. + /// + public double InchesPerMinute => As(SpeedUnit.InchPerMinute); + + /// + /// Get Speed in InchesPerSecond. + /// + public double InchesPerSecond => As(SpeedUnit.InchPerSecond); + + /// + /// Get Speed in KilometersPerHour. + /// + public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); + + /// + /// Get Speed in KilometersPerMinutes. + /// + public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); + + /// + /// Get Speed in KilometersPerSecond. + /// + public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); + + /// + /// Get Speed in Knots. + /// + public double Knots => As(SpeedUnit.Knot); + + /// + /// Get Speed in MetersPerHour. + /// + public double MetersPerHour => As(SpeedUnit.MeterPerHour); + + /// + /// Get Speed in MetersPerMinutes. + /// + public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); + + /// + /// Get Speed in MetersPerSecond. + /// + public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); + + /// + /// Get Speed in MicrometersPerMinutes. + /// + public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); + + /// + /// Get Speed in MicrometersPerSecond. + /// + public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); + + /// + /// Get Speed in MilesPerHour. + /// + public double MilesPerHour => As(SpeedUnit.MilePerHour); + + /// + /// Get Speed in MillimetersPerHour. + /// + public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); + + /// + /// Get Speed in MillimetersPerMinutes. + /// + public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); + + /// + /// Get Speed in MillimetersPerSecond. + /// + public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); + + /// + /// Get Speed in NanometersPerMinutes. + /// + public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); + + /// + /// Get Speed in NanometersPerSecond. + /// + public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); + + /// + /// Get Speed in UsSurveyFeetPerHour. + /// + public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); + + /// + /// Get Speed in UsSurveyFeetPerMinute. + /// + public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); + + /// + /// Get Speed in UsSurveyFeetPerSecond. + /// + public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); + + /// + /// Get Speed in YardsPerHour. + /// + public double YardsPerHour => As(SpeedUnit.YardPerHour); + /// - /// Get nullable Speed from nullable CentimetersPerSecond. + /// Get Speed in YardsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromCentimetersPerSecond(QuantityValue? centimeterspersecond) + public double YardsPerMinute => As(SpeedUnit.YardPerMinute); + + /// + /// Get Speed in YardsPerSecond. + /// + public double YardsPerSecond => As(SpeedUnit.YardPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(SpeedUnit unit) { - return centimeterspersecond.HasValue ? FromCentimetersPerSecond(centimeterspersecond.Value) : default(Speed?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Speed from nullable DecimetersPerMinutes. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromDecimetersPerMinutes(QuantityValue? decimetersperminutes) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] IFormatProvider provider) { - return decimetersperminutes.HasValue ? FromDecimetersPerMinutes(decimetersperminutes.Value) : default(Speed?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Speed from nullable DecimetersPerSecond. + /// Get Speed from CentimetersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromDecimetersPerSecond(QuantityValue? decimeterspersecond) + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) { - return decimeterspersecond.HasValue ? FromDecimetersPerSecond(decimeterspersecond.Value) : default(Speed?); + double value = (double) centimetersperhour; + return new Speed(value, SpeedUnit.CentimeterPerHour); } - /// - /// Get nullable Speed from nullable FeetPerHour. + /// Get Speed from CentimetersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromFeetPerHour(QuantityValue? feetperhour) + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) { - return feetperhour.HasValue ? FromFeetPerHour(feetperhour.Value) : default(Speed?); + double value = (double) centimetersperminutes; + return new Speed(value, SpeedUnit.CentimeterPerMinute); } - /// - /// Get nullable Speed from nullable FeetPerMinute. + /// Get Speed from CentimetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromFeetPerMinute(QuantityValue? feetperminute) + /// If value is NaN or Infinity. + public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) { - return feetperminute.HasValue ? FromFeetPerMinute(feetperminute.Value) : default(Speed?); + double value = (double) centimeterspersecond; + return new Speed(value, SpeedUnit.CentimeterPerSecond); } - /// - /// Get nullable Speed from nullable FeetPerSecond. + /// Get Speed from DecimetersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromFeetPerSecond(QuantityValue? feetpersecond) + /// If value is NaN or Infinity. + public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) { - return feetpersecond.HasValue ? FromFeetPerSecond(feetpersecond.Value) : default(Speed?); + double value = (double) decimetersperminutes; + return new Speed(value, SpeedUnit.DecimeterPerMinute); } - /// - /// Get nullable Speed from nullable InchesPerHour. + /// Get Speed from DecimetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromInchesPerHour(QuantityValue? inchesperhour) + /// If value is NaN or Infinity. + public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) { - return inchesperhour.HasValue ? FromInchesPerHour(inchesperhour.Value) : default(Speed?); + double value = (double) decimeterspersecond; + return new Speed(value, SpeedUnit.DecimeterPerSecond); } - /// - /// Get nullable Speed from nullable InchesPerMinute. + /// Get Speed from FeetPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromInchesPerMinute(QuantityValue? inchesperminute) + /// If value is NaN or Infinity. + public static Speed FromFeetPerHour(QuantityValue feetperhour) { - return inchesperminute.HasValue ? FromInchesPerMinute(inchesperminute.Value) : default(Speed?); + double value = (double) feetperhour; + return new Speed(value, SpeedUnit.FootPerHour); } - /// - /// Get nullable Speed from nullable InchesPerSecond. + /// Get Speed from FeetPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromInchesPerSecond(QuantityValue? inchespersecond) + /// If value is NaN or Infinity. + public static Speed FromFeetPerMinute(QuantityValue feetperminute) { - return inchespersecond.HasValue ? FromInchesPerSecond(inchespersecond.Value) : default(Speed?); + double value = (double) feetperminute; + return new Speed(value, SpeedUnit.FootPerMinute); } - /// - /// Get nullable Speed from nullable KilometersPerHour. + /// Get Speed from FeetPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromKilometersPerHour(QuantityValue? kilometersperhour) + /// If value is NaN or Infinity. + public static Speed FromFeetPerSecond(QuantityValue feetpersecond) { - return kilometersperhour.HasValue ? FromKilometersPerHour(kilometersperhour.Value) : default(Speed?); + double value = (double) feetpersecond; + return new Speed(value, SpeedUnit.FootPerSecond); } - /// - /// Get nullable Speed from nullable KilometersPerMinutes. + /// Get Speed from InchesPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromKilometersPerMinutes(QuantityValue? kilometersperminutes) + /// If value is NaN or Infinity. + public static Speed FromInchesPerHour(QuantityValue inchesperhour) { - return kilometersperminutes.HasValue ? FromKilometersPerMinutes(kilometersperminutes.Value) : default(Speed?); + double value = (double) inchesperhour; + return new Speed(value, SpeedUnit.InchPerHour); } - /// - /// Get nullable Speed from nullable KilometersPerSecond. + /// Get Speed from InchesPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromKilometersPerSecond(QuantityValue? kilometerspersecond) + /// If value is NaN or Infinity. + public static Speed FromInchesPerMinute(QuantityValue inchesperminute) { - return kilometerspersecond.HasValue ? FromKilometersPerSecond(kilometerspersecond.Value) : default(Speed?); + double value = (double) inchesperminute; + return new Speed(value, SpeedUnit.InchPerMinute); } - /// - /// Get nullable Speed from nullable Knots. + /// Get Speed from InchesPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromKnots(QuantityValue? knots) + /// If value is NaN or Infinity. + public static Speed FromInchesPerSecond(QuantityValue inchespersecond) { - return knots.HasValue ? FromKnots(knots.Value) : default(Speed?); + double value = (double) inchespersecond; + return new Speed(value, SpeedUnit.InchPerSecond); } - /// - /// Get nullable Speed from nullable MetersPerHour. + /// Get Speed from KilometersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMetersPerHour(QuantityValue? metersperhour) + /// If value is NaN or Infinity. + public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) { - return metersperhour.HasValue ? FromMetersPerHour(metersperhour.Value) : default(Speed?); + double value = (double) kilometersperhour; + return new Speed(value, SpeedUnit.KilometerPerHour); } - /// - /// Get nullable Speed from nullable MetersPerMinutes. + /// Get Speed from KilometersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMetersPerMinutes(QuantityValue? metersperminutes) + /// If value is NaN or Infinity. + public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) { - return metersperminutes.HasValue ? FromMetersPerMinutes(metersperminutes.Value) : default(Speed?); + double value = (double) kilometersperminutes; + return new Speed(value, SpeedUnit.KilometerPerMinute); } - /// - /// Get nullable Speed from nullable MetersPerSecond. + /// Get Speed from KilometersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMetersPerSecond(QuantityValue? meterspersecond) + /// If value is NaN or Infinity. + public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) { - return meterspersecond.HasValue ? FromMetersPerSecond(meterspersecond.Value) : default(Speed?); + double value = (double) kilometerspersecond; + return new Speed(value, SpeedUnit.KilometerPerSecond); } - /// - /// Get nullable Speed from nullable MicrometersPerMinutes. + /// Get Speed from Knots. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMicrometersPerMinutes(QuantityValue? micrometersperminutes) + /// If value is NaN or Infinity. + public static Speed FromKnots(QuantityValue knots) { - return micrometersperminutes.HasValue ? FromMicrometersPerMinutes(micrometersperminutes.Value) : default(Speed?); + double value = (double) knots; + return new Speed(value, SpeedUnit.Knot); } - /// - /// Get nullable Speed from nullable MicrometersPerSecond. + /// Get Speed from MetersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMicrometersPerSecond(QuantityValue? micrometerspersecond) + /// If value is NaN or Infinity. + public static Speed FromMetersPerHour(QuantityValue metersperhour) { - return micrometerspersecond.HasValue ? FromMicrometersPerSecond(micrometerspersecond.Value) : default(Speed?); + double value = (double) metersperhour; + return new Speed(value, SpeedUnit.MeterPerHour); } - /// - /// Get nullable Speed from nullable MilesPerHour. + /// Get Speed from MetersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMilesPerHour(QuantityValue? milesperhour) + /// If value is NaN or Infinity. + public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) { - return milesperhour.HasValue ? FromMilesPerHour(milesperhour.Value) : default(Speed?); + double value = (double) metersperminutes; + return new Speed(value, SpeedUnit.MeterPerMinute); } - /// - /// Get nullable Speed from nullable MillimetersPerHour. + /// Get Speed from MetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMillimetersPerHour(QuantityValue? millimetersperhour) + /// If value is NaN or Infinity. + public static Speed FromMetersPerSecond(QuantityValue meterspersecond) { - return millimetersperhour.HasValue ? FromMillimetersPerHour(millimetersperhour.Value) : default(Speed?); + double value = (double) meterspersecond; + return new Speed(value, SpeedUnit.MeterPerSecond); } - /// - /// Get nullable Speed from nullable MillimetersPerMinutes. + /// Get Speed from MicrometersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMillimetersPerMinutes(QuantityValue? millimetersperminutes) + /// If value is NaN or Infinity. + public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) { - return millimetersperminutes.HasValue ? FromMillimetersPerMinutes(millimetersperminutes.Value) : default(Speed?); + double value = (double) micrometersperminutes; + return new Speed(value, SpeedUnit.MicrometerPerMinute); } - /// - /// Get nullable Speed from nullable MillimetersPerSecond. + /// Get Speed from MicrometersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromMillimetersPerSecond(QuantityValue? millimeterspersecond) + /// If value is NaN or Infinity. + public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) { - return millimeterspersecond.HasValue ? FromMillimetersPerSecond(millimeterspersecond.Value) : default(Speed?); + double value = (double) micrometerspersecond; + return new Speed(value, SpeedUnit.MicrometerPerSecond); } - /// - /// Get nullable Speed from nullable NanometersPerMinutes. + /// Get Speed from MilesPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromNanometersPerMinutes(QuantityValue? nanometersperminutes) + /// If value is NaN or Infinity. + public static Speed FromMilesPerHour(QuantityValue milesperhour) { - return nanometersperminutes.HasValue ? FromNanometersPerMinutes(nanometersperminutes.Value) : default(Speed?); + double value = (double) milesperhour; + return new Speed(value, SpeedUnit.MilePerHour); } - /// - /// Get nullable Speed from nullable NanometersPerSecond. + /// Get Speed from MillimetersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromNanometersPerSecond(QuantityValue? nanometerspersecond) + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) { - return nanometerspersecond.HasValue ? FromNanometersPerSecond(nanometerspersecond.Value) : default(Speed?); + double value = (double) millimetersperhour; + return new Speed(value, SpeedUnit.MillimeterPerHour); } - /// - /// Get nullable Speed from nullable UsSurveyFeetPerHour. + /// Get Speed from MillimetersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromUsSurveyFeetPerHour(QuantityValue? ussurveyfeetperhour) + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) { - return ussurveyfeetperhour.HasValue ? FromUsSurveyFeetPerHour(ussurveyfeetperhour.Value) : default(Speed?); + double value = (double) millimetersperminutes; + return new Speed(value, SpeedUnit.MillimeterPerMinute); } - /// - /// Get nullable Speed from nullable UsSurveyFeetPerMinute. + /// Get Speed from MillimetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromUsSurveyFeetPerMinute(QuantityValue? ussurveyfeetperminute) + /// If value is NaN or Infinity. + public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) { - return ussurveyfeetperminute.HasValue ? FromUsSurveyFeetPerMinute(ussurveyfeetperminute.Value) : default(Speed?); + double value = (double) millimeterspersecond; + return new Speed(value, SpeedUnit.MillimeterPerSecond); } - /// - /// Get nullable Speed from nullable UsSurveyFeetPerSecond. + /// Get Speed from NanometersPerMinutes. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromUsSurveyFeetPerSecond(QuantityValue? ussurveyfeetpersecond) + /// If value is NaN or Infinity. + public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) { - return ussurveyfeetpersecond.HasValue ? FromUsSurveyFeetPerSecond(ussurveyfeetpersecond.Value) : default(Speed?); + double value = (double) nanometersperminutes; + return new Speed(value, SpeedUnit.NanometerPerMinute); } - /// - /// Get nullable Speed from nullable YardsPerHour. + /// Get Speed from NanometersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromYardsPerHour(QuantityValue? yardsperhour) + /// If value is NaN or Infinity. + public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) { - return yardsperhour.HasValue ? FromYardsPerHour(yardsperhour.Value) : default(Speed?); + double value = (double) nanometerspersecond; + return new Speed(value, SpeedUnit.NanometerPerSecond); } - /// - /// Get nullable Speed from nullable YardsPerMinute. + /// Get Speed from UsSurveyFeetPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromYardsPerMinute(QuantityValue? yardsperminute) + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) { - return yardsperminute.HasValue ? FromYardsPerMinute(yardsperminute.Value) : default(Speed?); + double value = (double) ussurveyfeetperhour; + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); + } + /// + /// Get Speed from UsSurveyFeetPerMinute. + /// + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) + { + double value = (double) ussurveyfeetperminute; + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); + } + /// + /// Get Speed from UsSurveyFeetPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) + { + double value = (double) ussurveyfeetpersecond; + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); + } + /// + /// Get Speed from YardsPerHour. + /// + /// If value is NaN or Infinity. + public static Speed FromYardsPerHour(QuantityValue yardsperhour) + { + double value = (double) yardsperhour; + return new Speed(value, SpeedUnit.YardPerHour); } - /// - /// Get nullable Speed from nullable YardsPerSecond. + /// Get Speed from YardsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Speed? FromYardsPerSecond(QuantityValue? yardspersecond) + /// If value is NaN or Infinity. + public static Speed FromYardsPerMinute(QuantityValue yardsperminute) { - return yardspersecond.HasValue ? FromYardsPerSecond(yardspersecond.Value) : default(Speed?); + double value = (double) yardsperminute; + return new Speed(value, SpeedUnit.YardPerMinute); + } + /// + /// Get Speed from YardsPerSecond. + /// + /// If value is NaN or Infinity. + public static Speed FromYardsPerSecond(QuantityValue yardspersecond) + { + double value = (double) yardspersecond; + return new Speed(value, SpeedUnit.YardPerSecond); } /// @@ -356,28 +631,156 @@ public partial struct Speed : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Speed unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Speed? From(QuantityValue? value, SpeedUnit fromUnit) + public static Speed From(QuantityValue value, SpeedUnit fromUnit) { - return value.HasValue ? new Speed((double)value.Value, fromUnit) : default(Speed?); + return new Speed((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Speed Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Speed result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Speed result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static SpeedUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static SpeedUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); } + public static bool TryParseUnit(string str, out SpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out SpeedUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Speed operator -(Speed right) @@ -417,6 +820,8 @@ public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] IFormatProvider #endregion + #region Equality / IComparable + public static bool operator <=(Speed left, Speed right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -437,180 +842,278 @@ public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] IFormatProvider return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Speed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Speed left, Speed right) + public static bool operator ==(Speed left, Speed right) + { + return left.Equals(right); + } + + public static bool operator !=(Speed left, Speed right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Speed, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Speed left, Speed right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(Speed other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Speed Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - SpeedUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromMetersPerSecond(x.MetersPerSecond + y.MetersPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Speed result) + /// A hash code for the current Speed. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Speed); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpeedUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Speed to another Speed with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Speed with the specified unit. + public Speed ToUnit(SpeedUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Speed(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpeedUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; + case SpeedUnit.FootPerHour: return _value*0.3048/3600; + case SpeedUnit.FootPerMinute: return _value*0.3048/60; + case SpeedUnit.FootPerSecond: return _value*0.3048; + case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; + case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; + case SpeedUnit.InchPerSecond: return _value*2.54e-2; + case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; + case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; + case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; + case SpeedUnit.Knot: return _value*0.514444; + case SpeedUnit.MeterPerHour: return _value/3600; + case SpeedUnit.MeterPerMinute: return _value/60; + case SpeedUnit.MeterPerSecond: return _value; + case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; + case SpeedUnit.MilePerHour: return _value*0.44704; + case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; + case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; + case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; + case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; + case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; + case SpeedUnit.YardPerHour: return _value*0.9144/3600; + case SpeedUnit.YardPerMinute: return _value*0.9144/60; + case SpeedUnit.YardPerSecond: return _value*0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(SpeedUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == SpeedUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpeedUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; + case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; + case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; + case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; + case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; + case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; + case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; + case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; + case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; + case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; + case SpeedUnit.Knot: return baseUnitValue/0.514444; + case SpeedUnit.MeterPerHour: return baseUnitValue*3600; + case SpeedUnit.MeterPerMinute: return baseUnitValue*60; + case SpeedUnit.MeterPerSecond: return baseUnitValue; + case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; + case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; + case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; + case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; + case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; + case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; + case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; + case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; + case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; + case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(SpeedUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs index 4cc4961ee8..6f4ad8306c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,158 +49,265 @@ namespace UnitsNet /// /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Temperature : IComparable, IComparable + public partial struct Temperature : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Temperature from nullable DegreesCelsius. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesCelsius(QuantityValue? degreescelsius) + private readonly TemperatureUnit? _unit; + + static Temperature() { - return degreescelsius.HasValue ? FromDegreesCelsius(degreescelsius.Value) : default(Temperature?); + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); } /// - /// Get nullable Temperature from nullable DegreesDelisle. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesDelisle(QuantityValue? degreesdelisle) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Temperature(double numericValue, TemperatureUnit unit) { - return degreesdelisle.HasValue ? FromDegreesDelisle(degreesdelisle.Value) : default(Temperature?); + if(unit == TemperatureUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + /// - /// Get nullable Temperature from nullable DegreesFahrenheit. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesFahrenheit(QuantityValue? degreesfahrenheit) - { - return degreesfahrenheit.HasValue ? FromDegreesFahrenheit(degreesfahrenheit.Value) : default(Temperature?); - } + public static BaseDimensions BaseDimensions { get; } /// - /// Get nullable Temperature from nullable DegreesNewton. + /// The base unit of Temperature, which is Kelvin. All conversions go via this value. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesNewton(QuantityValue? degreesnewton) - { - return degreesnewton.HasValue ? FromDegreesNewton(degreesnewton.Value) : default(Temperature?); - } + public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; /// - /// Get nullable Temperature from nullable DegreesRankine. + /// Represents the largest possible value of Temperature /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesRankine(QuantityValue? degreesrankine) - { - return degreesrankine.HasValue ? FromDegreesRankine(degreesrankine.Value) : default(Temperature?); - } + public static Temperature MaxValue => new Temperature(double.MaxValue, BaseUnit); /// - /// Get nullable Temperature from nullable DegreesReaumur. + /// Represents the smallest possible value of Temperature /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesReaumur(QuantityValue? degreesreaumur) - { - return degreesreaumur.HasValue ? FromDegreesReaumur(degreesreaumur.Value) : default(Temperature?); - } + public static Temperature MinValue => new Temperature(double.MinValue, BaseUnit); /// - /// Get nullable Temperature from nullable DegreesRoemer. + /// The of this quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromDegreesRoemer(QuantityValue? degreesroemer) - { - return degreesroemer.HasValue ? FromDegreesRoemer(degreesroemer.Value) : default(Temperature?); - } + public static QuantityType QuantityType => QuantityType.Temperature; /// - /// Get nullable Temperature from nullable Kelvins. + /// All units of measurement for the Temperature quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Temperature? FromKelvins(QuantityValue? kelvins) - { - return kelvins.HasValue ? FromKelvins(kelvins.Value) : default(Temperature?); - } + public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); /// - /// Dynamically convert from value and unit enum to . + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. /// - /// Value to convert from. - /// Unit to convert from. - /// Temperature unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Temperature? From(QuantityValue? value, TemperatureUnit fromUnit) - { - return value.HasValue ? new Temperature((double)value.Value, fromUnit) : default(Temperature?); - } + public static Temperature Zero => new Temperature(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Temperature.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Temperature.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Temperature in DegreesCelsius. + /// + public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); + + /// + /// Get Temperature in DegreesDelisle. + /// + public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); + + /// + /// Get Temperature in DegreesFahrenheit. + /// + public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); + + /// + /// Get Temperature in DegreesNewton. + /// + public double DegreesNewton => As(TemperatureUnit.DegreeNewton); + + /// + /// Get Temperature in DegreesRankine. + /// + public double DegreesRankine => As(TemperatureUnit.DegreeRankine); + + /// + /// Get Temperature in DegreesReaumur. + /// + public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); + + /// + /// Get Temperature in DegreesRoemer. + /// + public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); + + /// + /// Get Temperature in Kelvins. + /// + public double Kelvins => As(TemperatureUnit.Kelvin); #endregion + #region Static Methods + /// /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) + public static string GetAbbreviation(TemperatureUnit unit) { - provider = provider ?? UnitSystem.DefaultCulture; - - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + return GetAbbreviation(unit, null); } - public static bool operator <=(Temperature left, Temperature right) + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) { - return left.Value <= right.AsBaseNumericType(left.Unit); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - public static bool operator >=(Temperature left, Temperature right) + #endregion + + #region Static Factory Methods + + /// + /// Get Temperature from DegreesCelsius. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) { - return left.Value >= right.AsBaseNumericType(left.Unit); + double value = (double) degreescelsius; + return new Temperature(value, TemperatureUnit.DegreeCelsius); } - - public static bool operator <(Temperature left, Temperature right) + /// + /// Get Temperature from DegreesDelisle. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) { - return left.Value < right.AsBaseNumericType(left.Unit); + double value = (double) degreesdelisle; + return new Temperature(value, TemperatureUnit.DegreeDelisle); } - - public static bool operator >(Temperature left, Temperature right) + /// + /// Get Temperature from DegreesFahrenheit. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) { - return left.Value > right.AsBaseNumericType(left.Unit); + double value = (double) degreesfahrenheit; + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); } - - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Temperature, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Temperature left, Temperature right) + /// + /// Get Temperature from DegreesNewton. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesNewton(QuantityValue degreesnewton) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + double value = (double) degreesnewton; + return new Temperature(value, TemperatureUnit.DegreeNewton); + } + /// + /// Get Temperature from DegreesRankine. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesRankine(QuantityValue degreesrankine) + { + double value = (double) degreesrankine; + return new Temperature(value, TemperatureUnit.DegreeRankine); + } + /// + /// Get Temperature from DegreesReaumur. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) + { + double value = (double) degreesreaumur; + return new Temperature(value, TemperatureUnit.DegreeReaumur); + } + /// + /// Get Temperature from DegreesRoemer. + /// + /// If value is NaN or Infinity. + public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new Temperature(value, TemperatureUnit.DegreeRoemer); + } + /// + /// Get Temperature from Kelvins. + /// + /// If value is NaN or Infinity. + public static Temperature FromKelvins(QuantityValue kelvins) + { + double value = (double) kelvins; + return new Temperature(value, TemperatureUnit.Kelvin); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Temperature, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Temperature left, Temperature right) + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Temperature unit value. + public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return new Temperature((double)value, fromUnit); } - #region Parsing + #endregion + + #region Static Parse Methods /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -221,141 +326,371 @@ public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] IFormatPr /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Temperature Parse(string str, [CanBeNull] IFormatProvider provider) + public static Temperature Parse(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return Parse(str, null); + } - provider = provider ?? UnitSystem.DefaultCulture; + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Temperature Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {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} - /// Format to use when parsing number and unit. Defaults to . /// Resulting unit quantity if successful. + /// True if successful, otherwise false. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Temperature result) { - provider = provider ?? UnitSystem.DefaultCulture; - - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Temperature); - return false; - } + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) + public static TemperatureUnit ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureUnit ParseUnit(string str, IFormatProvider provider = null) { - if (str == null) throw new ArgumentNullException(nameof(str)); + return UnitParser.Default.Parse(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + public static bool TryParseUnit(string str, out TemperatureUnit unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == TemperatureUnit.Undefined) + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out TemperatureUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + + #region Equality / IComparable + + public static bool operator <=(Temperature left, Temperature right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=(Temperature left, Temperature right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <(Temperature left, Temperature right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >(Temperature left, Temperature right) + { + return left.Value > right.AsBaseNumericType(left.Unit); + } + + public static bool operator ==(Temperature left, Temperature right) + { + return left.Equals(right); + } + + public static bool operator !=(Temperature left, Temperature right) + { + return !(left == right); + } + + 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 + public int CompareTo(Temperature other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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 { QuantityType, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } + + /// + /// Converts this Temperature to another Temperature with the unit representation . + /// + /// A Temperature with the specified unit. + public Temperature ToUnit(TemperatureUnit unit) + { + var convertedValue = AsBaseNumericType(unit); + return new Temperature(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TemperatureUnit.DegreeCelsius: return _value + 273.15; + case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; + case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; + case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; + case TemperatureUnit.DegreeRankine: return _value*5/9; + case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; + case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; + case TemperatureUnit.Kelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); } + } - return unit; + private double AsBaseNumericType(TemperatureUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { + case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; + case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; + case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; + case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; + case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; + case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; + case TemperatureUnit.Kelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs index 9a6924eac7..40a63cb355 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,105 +49,272 @@ namespace UnitsNet /// /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct TemperatureChangeRate : IComparable, IComparable + public partial struct TemperatureChangeRate : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable TemperatureChangeRate from nullable CentidegreesCelsiusPerSecond. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromCentidegreesCelsiusPerSecond(QuantityValue? centidegreescelsiuspersecond) + private readonly TemperatureChangeRateUnit? _unit; + + static TemperatureChangeRate() { - return centidegreescelsiuspersecond.HasValue ? FromCentidegreesCelsiusPerSecond(centidegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); } /// - /// Get nullable TemperatureChangeRate from nullable DecadegreesCelsiusPerSecond. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromDecadegreesCelsiusPerSecond(QuantityValue? decadegreescelsiuspersecond) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public TemperatureChangeRate(double numericValue, TemperatureChangeRateUnit unit) { - return decadegreescelsiuspersecond.HasValue ? FromDecadegreesCelsiusPerSecond(decadegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + if(unit == TemperatureChangeRateUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. + /// + public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + + /// + /// Represents the largest possible value of TemperatureChangeRate + /// + public static TemperatureChangeRate MaxValue => new TemperatureChangeRate(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of TemperatureChangeRate + /// + public static TemperatureChangeRate MinValue => new TemperatureChangeRate(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.TemperatureChangeRate; + + /// + /// All units of measurement for the TemperatureChangeRate quantity. + /// + public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// + public static TemperatureChangeRate Zero => new TemperatureChangeRate(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureChangeRate.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get TemperatureChangeRate in CentidegreesCelsiusPerSecond. + /// + public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DecadegreesCelsiusPerSecond. + /// + public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DecidegreesCelsiusPerSecond. + /// + public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in DegreesCelsiusPerMinute. + /// + public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + + /// + /// Get TemperatureChangeRate in DegreesCelsiusPerSecond. + /// + public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in HectodegreesCelsiusPerSecond. + /// + public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in KilodegreesCelsiusPerSecond. + /// + public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in MicrodegreesCelsiusPerSecond. + /// + public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in MillidegreesCelsiusPerSecond. + /// + public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + + /// + /// Get TemperatureChangeRate in NanodegreesCelsiusPerSecond. + /// + public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + + #endregion + + #region Static Methods + /// - /// Get nullable TemperatureChangeRate from nullable DecidegreesCelsiusPerSecond. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromDecidegreesCelsiusPerSecond(QuantityValue? decidegreescelsiuspersecond) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureChangeRateUnit unit) { - return decidegreescelsiuspersecond.HasValue ? FromDecidegreesCelsiusPerSecond(decidegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + return GetAbbreviation(unit, null); } /// - /// Get nullable TemperatureChangeRate from nullable DegreesCelsiusPerMinute. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromDegreesCelsiusPerMinute(QuantityValue? degreescelsiusperminute) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) { - return degreescelsiusperminute.HasValue ? FromDegreesCelsiusPerMinute(degreescelsiusperminute.Value) : default(TemperatureChangeRate?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable TemperatureChangeRate from nullable DegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromDegreesCelsiusPerSecond(QuantityValue? degreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) { - return degreescelsiuspersecond.HasValue ? FromDegreesCelsiusPerSecond(degreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) centidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); } - /// - /// Get nullable TemperatureChangeRate from nullable HectodegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromHectodegreesCelsiusPerSecond(QuantityValue? hectodegreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) { - return hectodegreescelsiuspersecond.HasValue ? FromHectodegreesCelsiusPerSecond(hectodegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) decadegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); } - /// - /// Get nullable TemperatureChangeRate from nullable KilodegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromKilodegreesCelsiusPerSecond(QuantityValue? kilodegreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) { - return kilodegreescelsiuspersecond.HasValue ? FromKilodegreesCelsiusPerSecond(kilodegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) decidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); } - /// - /// Get nullable TemperatureChangeRate from nullable MicrodegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromMicrodegreesCelsiusPerSecond(QuantityValue? microdegreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) { - return microdegreescelsiuspersecond.HasValue ? FromMicrodegreesCelsiusPerSecond(microdegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) degreescelsiusperminute; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); } - /// - /// Get nullable TemperatureChangeRate from nullable MillidegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromMillidegreesCelsiusPerSecond(QuantityValue? millidegreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) { - return millidegreescelsiuspersecond.HasValue ? FromMillidegreesCelsiusPerSecond(millidegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) degreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); } - /// - /// Get nullable TemperatureChangeRate from nullable NanodegreesCelsiusPerSecond. + /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureChangeRate? FromNanodegreesCelsiusPerSecond(QuantityValue? nanodegreescelsiuspersecond) + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) { - return nanodegreescelsiuspersecond.HasValue ? FromNanodegreesCelsiusPerSecond(nanodegreescelsiuspersecond.Value) : default(TemperatureChangeRate?); + double value = (double) hectodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) + { + double value = (double) kilodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) + { + double value = (double) microdegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) + { + double value = (double) millidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + } + /// + /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. + /// + /// If value is NaN or Infinity. + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) + { + double value = (double) nanodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); } /// @@ -158,28 +323,156 @@ public partial struct TemperatureChangeRate : IComparable, IComparableValue to convert from. /// Unit to convert from. /// TemperatureChangeRate unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureChangeRate? From(QuantityValue? value, TemperatureChangeRateUnit fromUnit) + public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) { - return value.HasValue ? new TemperatureChangeRate((double)value.Value, fromUnit) : default(TemperatureChangeRate?); + return new TemperatureChangeRate((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static TemperatureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) + { + return TryParse(str, null, out result); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureChangeRate result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static TemperatureChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out TemperatureChangeRateUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static TemperatureChangeRate operator -(TemperatureChangeRate right) @@ -219,6 +512,8 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] #endregion + #region Equality / IComparable + public static bool operator <=(TemperatureChangeRate left, TemperatureChangeRate right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -239,180 +534,234 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) + public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureChangeRate, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) + public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(TemperatureChangeRate other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureChangeRate Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureChangeRateUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromDegreesCelsiusPerSecond(x.DegreesCelsiusPerSecond + y.DegreesCelsiusPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureChangeRate result) + /// A hash code for the current TemperatureChangeRate. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(TemperatureChangeRate); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureChangeRateUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A TemperatureChangeRate with the specified unit. + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new TemperatureChangeRate(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + 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."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(TemperatureChangeRateUnit unit) + { + if(Unit == unit) + return _value; - if (unit == TemperatureChangeRateUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureChangeRateUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + 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}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs index 9056104927..b30f38b0c6 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,189 +49,402 @@ namespace UnitsNet /// /// Difference between two temperatures. The conversions are different than for Temperature. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct TemperatureDelta : IComparable, IComparable + public partial struct TemperatureDelta : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable TemperatureDelta from nullable DegreesCelsius. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesCelsius(QuantityValue? degreescelsius) + private readonly TemperatureDeltaUnit? _unit; + + static TemperatureDelta() { - return degreescelsius.HasValue ? FromDegreesCelsius(degreescelsius.Value) : default(TemperatureDelta?); + BaseDimensions = BaseDimensions.Dimensionless; } /// - /// Get nullable TemperatureDelta from nullable DegreesCelsiusDelta. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesCelsiusDelta(QuantityValue? degreescelsiusdelta) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public TemperatureDelta(double numericValue, TemperatureDeltaUnit unit) { - return degreescelsiusdelta.HasValue ? FromDegreesCelsiusDelta(degreescelsiusdelta.Value) : default(TemperatureDelta?); + if(unit == TemperatureDeltaUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. + /// + public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; + + /// + /// Represents the largest possible value of TemperatureDelta + /// + public static TemperatureDelta MaxValue => new TemperatureDelta(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of TemperatureDelta + /// + public static TemperatureDelta MinValue => new TemperatureDelta(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.TemperatureDelta; + + /// + /// All units of measurement for the TemperatureDelta quantity. + /// + public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// + public static TemperatureDelta Zero => new TemperatureDelta(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => TemperatureDelta.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get TemperatureDelta in DegreesCelsius. + /// + public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); + + /// + /// Get TemperatureDelta in DegreesDelisle. + /// + public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); + + /// + /// Get TemperatureDelta in DegreesFahrenheit. + /// + public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); + + /// + /// Get TemperatureDelta in DegreesNewton. + /// + public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); + + /// + /// Get TemperatureDelta in DegreesRankine. + /// + public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); + + /// + /// Get TemperatureDelta in DegreesReaumur. + /// + public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); + + /// + /// Get TemperatureDelta in DegreesRoemer. + /// + public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); + + /// + /// Get TemperatureDelta in Kelvins. + /// + public double Kelvins => As(TemperatureDeltaUnit.Kelvin); + + #endregion + + #region Static Methods + /// - /// Get nullable TemperatureDelta from nullable DegreesDelisle. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesDelisle(QuantityValue? degreesdelisle) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TemperatureDeltaUnit unit) { - return degreesdelisle.HasValue ? FromDegreesDelisle(degreesdelisle.Value) : default(TemperatureDelta?); + return GetAbbreviation(unit, null); } /// - /// Get nullable TemperatureDelta from nullable DegreesDelisleDelta. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesDelisleDelta(QuantityValue? degreesdelisledelta) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider) { - return degreesdelisledelta.HasValue ? FromDegreesDelisleDelta(degreesdelisledelta.Value) : default(TemperatureDelta?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable TemperatureDelta from nullable DegreesFahrenheit. + /// Get TemperatureDelta from DegreesCelsius. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesFahrenheit(QuantityValue? degreesfahrenheit) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) { - return degreesfahrenheit.HasValue ? FromDegreesFahrenheit(degreesfahrenheit.Value) : default(TemperatureDelta?); + double value = (double) degreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); } - /// - /// Get nullable TemperatureDelta from nullable DegreesFahrenheitDelta. + /// Get TemperatureDelta from DegreesDelisle. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesFahrenheitDelta(QuantityValue? degreesfahrenheitdelta) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) { - return degreesfahrenheitdelta.HasValue ? FromDegreesFahrenheitDelta(degreesfahrenheitdelta.Value) : default(TemperatureDelta?); + double value = (double) degreesdelisle; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); } - /// - /// Get nullable TemperatureDelta from nullable DegreesNewton. + /// Get TemperatureDelta from DegreesFahrenheit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesNewton(QuantityValue? degreesnewton) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) { - return degreesnewton.HasValue ? FromDegreesNewton(degreesnewton.Value) : default(TemperatureDelta?); + double value = (double) degreesfahrenheit; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); } - /// - /// Get nullable TemperatureDelta from nullable DegreesNewtonDelta. + /// Get TemperatureDelta from DegreesNewton. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesNewtonDelta(QuantityValue? degreesnewtondelta) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) { - return degreesnewtondelta.HasValue ? FromDegreesNewtonDelta(degreesnewtondelta.Value) : default(TemperatureDelta?); + double value = (double) degreesnewton; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); } - /// - /// Get nullable TemperatureDelta from nullable DegreesRankine. + /// Get TemperatureDelta from DegreesRankine. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesRankine(QuantityValue? degreesrankine) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) { - return degreesrankine.HasValue ? FromDegreesRankine(degreesrankine.Value) : default(TemperatureDelta?); + double value = (double) degreesrankine; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); } - /// - /// Get nullable TemperatureDelta from nullable DegreesRankineDelta. + /// Get TemperatureDelta from DegreesReaumur. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesRankineDelta(QuantityValue? degreesrankinedelta) + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) { - return degreesrankinedelta.HasValue ? FromDegreesRankineDelta(degreesrankinedelta.Value) : default(TemperatureDelta?); + double value = (double) degreesreaumur; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); + } + /// + /// Get TemperatureDelta from DegreesRoemer. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); + } + /// + /// Get TemperatureDelta from Kelvins. + /// + /// If value is NaN or Infinity. + public static TemperatureDelta FromKelvins(QuantityValue kelvins) + { + double value = (double) kelvins; + return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); } /// - /// Get nullable TemperatureDelta from nullable DegreesReaumur. + /// Dynamically convert from value and unit enum to . /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesReaumur(QuantityValue? degreesreaumur) + /// Value to convert from. + /// Unit to convert from. + /// TemperatureDelta unit value. + public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) { - return degreesreaumur.HasValue ? FromDegreesReaumur(degreesreaumur.Value) : default(TemperatureDelta?); + return new TemperatureDelta((double)value, fromUnit); } + #endregion + + #region Static Parse Methods + /// - /// Get nullable TemperatureDelta from nullable DegreesReaumurDelta. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesReaumurDelta(QuantityValue? degreesreaumurdelta) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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 degreesreaumurdelta.HasValue ? FromDegreesReaumurDelta(degreesreaumurdelta.Value) : default(TemperatureDelta?); + return Parse(str, null); } /// - /// Get nullable TemperatureDelta from nullable DegreesRoemer. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesRoemer(QuantityValue? degreesroemer) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static TemperatureDelta Parse(string str, [CanBeNull] IFormatProvider provider) { - return degreesroemer.HasValue ? FromDegreesRoemer(degreesroemer.Value) : default(TemperatureDelta?); + return QuantityParser.Default.Parse( + str, + provider, + From); } /// - /// Get nullable TemperatureDelta from nullable DegreesRoemerDelta. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromDegreesRoemerDelta(QuantityValue? degreesroemerdelta) + /// String to parse. Typically in the form: {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 degreesroemerdelta.HasValue ? FromDegreesRoemerDelta(degreesroemerdelta.Value) : default(TemperatureDelta?); + return TryParse(str, null, out result); } /// - /// Get nullable TemperatureDelta from nullable Kelvins. + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromKelvins(QuantityValue? kelvins) + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureDelta result) { - return kelvins.HasValue ? FromKelvins(kelvins.Value) : default(TemperatureDelta?); + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); } /// - /// Get nullable TemperatureDelta from nullable KelvinsDelta. + /// Parse a unit string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static TemperatureDelta? FromKelvinsDelta(QuantityValue? kelvinsdelta) + /// String to parse. Typically 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 kelvinsdelta.HasValue ? FromKelvinsDelta(kelvinsdelta.Value) : default(TemperatureDelta?); + return ParseUnit(str, null); } /// - /// Dynamically convert from value and unit enum to . + /// Parse a unit string. /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureDelta unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static TemperatureDelta? From(QuantityValue? value, TemperatureDeltaUnit fromUnit) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider provider = null) { - return value.HasValue ? new TemperatureDelta((double)value.Value, fromUnit) : default(TemperatureDelta?); + return UnitParser.Default.Parse(str, provider); } - #endregion + public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) + { + return TryParseUnit(str, null, out unit); + } /// - /// Get unit abbreviation string. + /// Parse a unit string. /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out TemperatureDeltaUnit unit) { - provider = provider ?? UnitSystem.DefaultCulture; - - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + return UnitParser.Default.TryParse(str, provider, out unit); } + #endregion + #region Arithmetic Operators public static TemperatureDelta operator -(TemperatureDelta right) @@ -273,6 +484,8 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] IFor #endregion + #region Equality / IComparable + public static bool operator <=(TemperatureDelta left, TemperatureDelta right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -293,180 +506,230 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] IFor return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureDelta, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(TemperatureDelta left, TemperatureDelta right) + public static bool operator ==(TemperatureDelta left, TemperatureDelta right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(TemperatureDelta, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(TemperatureDelta left, TemperatureDelta right) + public static bool operator !=(TemperatureDelta left, TemperatureDelta right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(TemperatureDelta other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureDelta Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TemperatureDeltaUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureDelta result) + /// A hash code for the current TemperatureDelta. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(TemperatureDelta); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureDeltaUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A TemperatureDelta with the specified unit. + public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new TemperatureDelta(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case TemperatureDeltaUnit.DegreeCelsius: return _value; + case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; + case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; + case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; + case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; + case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; + case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; + case TemperatureDeltaUnit.Kelvin: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(TemperatureDeltaUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == TemperatureDeltaUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureDeltaUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; + case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; + case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; + case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; + case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; + case TemperatureDeltaUnit.Kelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs index 7e80f0cf1e..77ee8a8895 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,33 +49,163 @@ namespace UnitsNet /// /// Thermal conductivity is the property of a material to conduct heat. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ThermalConductivity : IComparable, IComparable + /// + /// https://en.wikipedia.org/wiki/Thermal_Conductivity + /// + public partial struct ThermalConductivity : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalConductivityUnit? _unit; + + static ThermalConductivity() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ThermalConductivity(double numericValue, ThermalConductivityUnit unit) + { + if(unit == ThermalConductivityUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. + /// + public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; + + /// + /// Represents the largest possible value of ThermalConductivity + /// + public static ThermalConductivity MaxValue => new ThermalConductivity(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ThermalConductivity + /// + public static ThermalConductivity MinValue => new ThermalConductivity(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ThermalConductivity; + + /// + /// All units of measurement for the ThermalConductivity quantity. + /// + public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// + public static ThermalConductivity Zero => new ThermalConductivity(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalConductivity.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties /// - /// Get nullable ThermalConductivity from nullable BtusPerHourFootFahrenheit. + /// Get ThermalConductivity in BtusPerHourFootFahrenheit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalConductivity? FromBtusPerHourFootFahrenheit(QuantityValue? btusperhourfootfahrenheit) + public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + + /// + /// Get ThermalConductivity in WattsPerMeterKelvin. + /// + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalConductivityUnit unit) { - return btusperhourfootfahrenheit.HasValue ? FromBtusPerHourFootFahrenheit(btusperhourfootfahrenheit.Value) : default(ThermalConductivity?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ThermalConductivity from nullable WattsPerMeterKelvin. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalConductivity? FromWattsPerMeterKelvin(QuantityValue? wattspermeterkelvin) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider) { - return wattspermeterkelvin.HasValue ? FromWattsPerMeterKelvin(wattspermeterkelvin.Value) : default(ThermalConductivity?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalConductivity from BtusPerHourFootFahrenheit. + /// + /// If value is NaN or Infinity. + public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) + { + double value = (double) btusperhourfootfahrenheit; + return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); + } + /// + /// Get ThermalConductivity from WattsPerMeterKelvin. + /// + /// If value is NaN or Infinity. + public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) + { + double value = (double) wattspermeterkelvin; + return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); } /// @@ -86,28 +214,156 @@ public partial struct ThermalConductivity : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ThermalConductivity unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalConductivity? From(QuantityValue? value, ThermalConductivityUnit fromUnit) + public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) { - return value.HasValue ? new ThermalConductivity((double)value.Value, fromUnit) : default(ThermalConductivity?); + return new ThermalConductivity((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ThermalConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalConductivity result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ThermalConductivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ThermalConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ThermalConductivityUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ThermalConductivity operator -(ThermalConductivity right) @@ -147,6 +403,8 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] I #endregion + #region Equality / IComparable + public static bool operator <=(ThermalConductivity left, ThermalConductivity right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -167,180 +425,218 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] I return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ThermalConductivity left, ThermalConductivity right) + public static bool operator ==(ThermalConductivity left, ThermalConductivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalConductivity, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ThermalConductivity left, ThermalConductivity right) + public static bool operator !=(ThermalConductivity left, ThermalConductivity right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(ThermalConductivity other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalConductivity Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ThermalConductivity other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ThermalConductivityUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromWattsPerMeterKelvin(x.WattsPerMeterKelvin + y.WattsPerMeterKelvin)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalConductivity result) + /// A hash code for the current ThermalConductivity. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ThermalConductivity); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalConductivityUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ThermalConductivity with the specified unit. + public ThermalConductivity ToUnit(ThermalConductivityUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ThermalConductivity(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalConductivityUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ThermalConductivityUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalConductivityUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return baseUnitValue/1.73073467; + case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs index 5f182efae8..1c7fd72572 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,60 +49,202 @@ namespace UnitsNet /// /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct ThermalResistance : IComparable, IComparable + public partial struct ThermalResistance : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable ThermalResistance from nullable HourSquareFeetDegreesFahrenheitPerBtu. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalResistance? FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue? hoursquarefeetdegreesfahrenheitperbtu) + private readonly ThermalResistanceUnit? _unit; + + static ThermalResistance() { - return hoursquarefeetdegreesfahrenheitperbtu.HasValue ? FromHourSquareFeetDegreesFahrenheitPerBtu(hoursquarefeetdegreesfahrenheitperbtu.Value) : default(ThermalResistance?); + BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); } /// - /// Get nullable ThermalResistance from nullable SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalResistance? FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue? squarecentimeterhourdegreescelsiusperkilocalorie) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public ThermalResistance(double numericValue, ThermalResistanceUnit unit) { - return squarecentimeterhourdegreescelsiusperkilocalorie.HasValue ? FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(squarecentimeterhourdegreescelsiusperkilocalorie.Value) : default(ThermalResistance?); + if(unit == ThermalResistanceUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. + /// + public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; + + /// + /// Represents the largest possible value of ThermalResistance + /// + public static ThermalResistance MaxValue => new ThermalResistance(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of ThermalResistance + /// + public static ThermalResistance MinValue => new ThermalResistance(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.ThermalResistance; + + /// + /// All units of measurement for the ThermalResistance quantity. + /// + public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// + public static ThermalResistance Zero => new ThermalResistance(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => ThermalResistance.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get ThermalResistance in HourSquareFeetDegreesFahrenheitPerBtu. + /// + public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + + /// + /// Get ThermalResistance in SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + + /// + /// Get ThermalResistance in SquareCentimeterKelvinsPerWatt. + /// + public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + + /// + /// Get ThermalResistance in SquareMeterDegreesCelsiusPerWatt. + /// + public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + + /// + /// Get ThermalResistance in SquareMeterKelvinsPerKilowatt. + /// + public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + + #endregion + + #region Static Methods + /// - /// Get nullable ThermalResistance from nullable SquareCentimeterKelvinsPerWatt. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalResistance? FromSquareCentimeterKelvinsPerWatt(QuantityValue? squarecentimeterkelvinsperwatt) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(ThermalResistanceUnit unit) { - return squarecentimeterkelvinsperwatt.HasValue ? FromSquareCentimeterKelvinsPerWatt(squarecentimeterkelvinsperwatt.Value) : default(ThermalResistance?); + return GetAbbreviation(unit, null); } /// - /// Get nullable ThermalResistance from nullable SquareMeterDegreesCelsiusPerWatt. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalResistance? FromSquareMeterDegreesCelsiusPerWatt(QuantityValue? squaremeterdegreescelsiusperwatt) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider) { - return squaremeterdegreescelsiusperwatt.HasValue ? FromSquareMeterDegreesCelsiusPerWatt(squaremeterdegreescelsiusperwatt.Value) : default(ThermalResistance?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + + /// + /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) + { + double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + } + /// + /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) + { + double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + } + /// + /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) + { + double value = (double) squarecentimeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + } + /// + /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. + /// + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) + { + double value = (double) squaremeterdegreescelsiusperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + } /// - /// Get nullable ThermalResistance from nullable SquareMeterKelvinsPerKilowatt. + /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static ThermalResistance? FromSquareMeterKelvinsPerKilowatt(QuantityValue? squaremeterkelvinsperkilowatt) + /// If value is NaN or Infinity. + public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) { - return squaremeterkelvinsperkilowatt.HasValue ? FromSquareMeterKelvinsPerKilowatt(squaremeterkelvinsperkilowatt.Value) : default(ThermalResistance?); + double value = (double) squaremeterkelvinsperkilowatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); } /// @@ -113,28 +253,156 @@ public partial struct ThermalResistance : IComparable, IComparableValue to convert from. /// Unit to convert from. /// ThermalResistance unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static ThermalResistance? From(QuantityValue? value, ThermalResistanceUnit fromUnit) + public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) { - return value.HasValue ? new ThermalResistance((double)value.Value, fromUnit) : default(ThermalResistance?); + return new ThermalResistance((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static ThermalResistance Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out ThermalResistance result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalResistance result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static ThermalResistanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static ThermalResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out ThermalResistanceUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static ThermalResistance operator -(ThermalResistance right) @@ -174,6 +442,8 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] IFo #endregion + #region Equality / IComparable + public static bool operator <=(ThermalResistance left, ThermalResistance right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -194,180 +464,224 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] IFo return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(ThermalResistance left, ThermalResistance right) + public static bool operator ==(ThermalResistance left, ThermalResistance right) + { + return left.Equals(right); + } + + public static bool operator !=(ThermalResistance left, ThermalResistance right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return !(left == right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(ThermalResistance, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(ThermalResistance left, ThermalResistance right) + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + 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); } - #region Parsing + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(ThermalResistance other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalResistance Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(ThermalResistance other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - ThermalResistanceUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromSquareMeterKelvinsPerKilowatt(x.SquareMeterKelvinsPerKilowatt + y.SquareMeterKelvinsPerKilowatt)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ThermalResistance result) + /// A hash code for the current ThermalResistance. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(ThermalResistance); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalResistanceUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this ThermalResistance to another ThermalResistance with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A ThermalResistance with the specified unit. + public ThermalResistance ToUnit(ThermalResistanceUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new ThermalResistance(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalResistanceUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() + { + switch(Unit) + { + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(ThermalResistanceUnit unit) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == ThermalResistanceUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalResistanceUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs index ae445403b7..a73e74b5fc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,204 +49,426 @@ namespace UnitsNet /// /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Torque : IComparable, IComparable + public partial struct Torque : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Torque from nullable KilogramForceCentimeters. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilogramForceCentimeters(QuantityValue? kilogramforcecentimeters) + private readonly TorqueUnit? _unit; + + static Torque() { - return kilogramforcecentimeters.HasValue ? FromKilogramForceCentimeters(kilogramforcecentimeters.Value) : default(Torque?); + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); } /// - /// Get nullable Torque from nullable KilogramForceMeters. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilogramForceMeters(QuantityValue? kilogramforcemeters) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Torque(double numericValue, TorqueUnit unit) { - return kilogramforcemeters.HasValue ? FromKilogramForceMeters(kilogramforcemeters.Value) : default(Torque?); + if(unit == TorqueUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. + /// + public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; + + /// + /// Represents the largest possible value of Torque + /// + public static Torque MaxValue => new Torque(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Torque + /// + public static Torque MinValue => new Torque(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Torque; + + /// + /// All units of measurement for the Torque quantity. + /// + public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. + /// + public static Torque Zero => new Torque(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Torque.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Torque.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Torque in KilogramForceCentimeters. + /// + public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); + + /// + /// Get Torque in KilogramForceMeters. + /// + public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); + + /// + /// Get Torque in KilogramForceMillimeters. + /// + public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); + + /// + /// Get Torque in KilonewtonCentimeters. + /// + public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); + + /// + /// Get Torque in KilonewtonMeters. + /// + public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); + + /// + /// Get Torque in KilonewtonMillimeters. + /// + public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); + + /// + /// Get Torque in KilopoundForceFeet. + /// + public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); + + /// + /// Get Torque in KilopoundForceInches. + /// + public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); + + /// + /// Get Torque in MeganewtonCentimeters. + /// + public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); + + /// + /// Get Torque in MeganewtonMeters. + /// + public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); + + /// + /// Get Torque in MeganewtonMillimeters. + /// + public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); + + /// + /// Get Torque in MegapoundForceFeet. + /// + public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); + + /// + /// Get Torque in MegapoundForceInches. + /// + public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); + + /// + /// Get Torque in NewtonCentimeters. + /// + public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); + + /// + /// Get Torque in NewtonMeters. + /// + public double NewtonMeters => As(TorqueUnit.NewtonMeter); + + /// + /// Get Torque in NewtonMillimeters. + /// + public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); + + /// + /// Get Torque in PoundForceFeet. + /// + public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); + + /// + /// Get Torque in PoundForceInches. + /// + public double PoundForceInches => As(TorqueUnit.PoundForceInch); + + /// + /// Get Torque in TonneForceCentimeters. + /// + public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); + + /// + /// Get Torque in TonneForceMeters. + /// + public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); + + /// + /// Get Torque in TonneForceMillimeters. + /// + public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); + + #endregion + + #region Static Methods + /// - /// Get nullable Torque from nullable KilogramForceMillimeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilogramForceMillimeters(QuantityValue? kilogramforcemillimeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(TorqueUnit unit) { - return kilogramforcemillimeters.HasValue ? FromKilogramForceMillimeters(kilogramforcemillimeters.Value) : default(Torque?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Torque from nullable KilonewtonCentimeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilonewtonCentimeters(QuantityValue? kilonewtoncentimeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] IFormatProvider provider) { - return kilonewtoncentimeters.HasValue ? FromKilonewtonCentimeters(kilonewtoncentimeters.Value) : default(Torque?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Torque from nullable KilonewtonMeters. + /// Get Torque from KilogramForceCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilonewtonMeters(QuantityValue? kilonewtonmeters) + /// If value is NaN or Infinity. + public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) { - return kilonewtonmeters.HasValue ? FromKilonewtonMeters(kilonewtonmeters.Value) : default(Torque?); + double value = (double) kilogramforcecentimeters; + return new Torque(value, TorqueUnit.KilogramForceCentimeter); } - /// - /// Get nullable Torque from nullable KilonewtonMillimeters. + /// Get Torque from KilogramForceMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilonewtonMillimeters(QuantityValue? kilonewtonmillimeters) + /// If value is NaN or Infinity. + public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) { - return kilonewtonmillimeters.HasValue ? FromKilonewtonMillimeters(kilonewtonmillimeters.Value) : default(Torque?); + double value = (double) kilogramforcemeters; + return new Torque(value, TorqueUnit.KilogramForceMeter); } - /// - /// Get nullable Torque from nullable KilopoundForceFeet. + /// Get Torque from KilogramForceMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilopoundForceFeet(QuantityValue? kilopoundforcefeet) + /// If value is NaN or Infinity. + public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) { - return kilopoundforcefeet.HasValue ? FromKilopoundForceFeet(kilopoundforcefeet.Value) : default(Torque?); + double value = (double) kilogramforcemillimeters; + return new Torque(value, TorqueUnit.KilogramForceMillimeter); } - /// - /// Get nullable Torque from nullable KilopoundForceInches. + /// Get Torque from KilonewtonCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromKilopoundForceInches(QuantityValue? kilopoundforceinches) + /// If value is NaN or Infinity. + public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) { - return kilopoundforceinches.HasValue ? FromKilopoundForceInches(kilopoundforceinches.Value) : default(Torque?); + double value = (double) kilonewtoncentimeters; + return new Torque(value, TorqueUnit.KilonewtonCentimeter); } - /// - /// Get nullable Torque from nullable MeganewtonCentimeters. + /// Get Torque from KilonewtonMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromMeganewtonCentimeters(QuantityValue? meganewtoncentimeters) + /// If value is NaN or Infinity. + public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) { - return meganewtoncentimeters.HasValue ? FromMeganewtonCentimeters(meganewtoncentimeters.Value) : default(Torque?); + double value = (double) kilonewtonmeters; + return new Torque(value, TorqueUnit.KilonewtonMeter); } - /// - /// Get nullable Torque from nullable MeganewtonMeters. + /// Get Torque from KilonewtonMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromMeganewtonMeters(QuantityValue? meganewtonmeters) + /// If value is NaN or Infinity. + public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) { - return meganewtonmeters.HasValue ? FromMeganewtonMeters(meganewtonmeters.Value) : default(Torque?); + double value = (double) kilonewtonmillimeters; + return new Torque(value, TorqueUnit.KilonewtonMillimeter); } - /// - /// Get nullable Torque from nullable MeganewtonMillimeters. + /// Get Torque from KilopoundForceFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromMeganewtonMillimeters(QuantityValue? meganewtonmillimeters) + /// If value is NaN or Infinity. + public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) { - return meganewtonmillimeters.HasValue ? FromMeganewtonMillimeters(meganewtonmillimeters.Value) : default(Torque?); + double value = (double) kilopoundforcefeet; + return new Torque(value, TorqueUnit.KilopoundForceFoot); } - /// - /// Get nullable Torque from nullable MegapoundForceFeet. + /// Get Torque from KilopoundForceInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromMegapoundForceFeet(QuantityValue? megapoundforcefeet) + /// If value is NaN or Infinity. + public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) { - return megapoundforcefeet.HasValue ? FromMegapoundForceFeet(megapoundforcefeet.Value) : default(Torque?); + double value = (double) kilopoundforceinches; + return new Torque(value, TorqueUnit.KilopoundForceInch); } - /// - /// Get nullable Torque from nullable MegapoundForceInches. + /// Get Torque from MeganewtonCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromMegapoundForceInches(QuantityValue? megapoundforceinches) + /// If value is NaN or Infinity. + public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) { - return megapoundforceinches.HasValue ? FromMegapoundForceInches(megapoundforceinches.Value) : default(Torque?); + double value = (double) meganewtoncentimeters; + return new Torque(value, TorqueUnit.MeganewtonCentimeter); } - /// - /// Get nullable Torque from nullable NewtonCentimeters. + /// Get Torque from MeganewtonMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromNewtonCentimeters(QuantityValue? newtoncentimeters) + /// If value is NaN or Infinity. + public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) { - return newtoncentimeters.HasValue ? FromNewtonCentimeters(newtoncentimeters.Value) : default(Torque?); + double value = (double) meganewtonmeters; + return new Torque(value, TorqueUnit.MeganewtonMeter); } - /// - /// Get nullable Torque from nullable NewtonMeters. + /// Get Torque from MeganewtonMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromNewtonMeters(QuantityValue? newtonmeters) + /// If value is NaN or Infinity. + public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) { - return newtonmeters.HasValue ? FromNewtonMeters(newtonmeters.Value) : default(Torque?); + double value = (double) meganewtonmillimeters; + return new Torque(value, TorqueUnit.MeganewtonMillimeter); } - /// - /// Get nullable Torque from nullable NewtonMillimeters. + /// Get Torque from MegapoundForceFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromNewtonMillimeters(QuantityValue? newtonmillimeters) + /// If value is NaN or Infinity. + public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) { - return newtonmillimeters.HasValue ? FromNewtonMillimeters(newtonmillimeters.Value) : default(Torque?); + double value = (double) megapoundforcefeet; + return new Torque(value, TorqueUnit.MegapoundForceFoot); } - /// - /// Get nullable Torque from nullable PoundForceFeet. + /// Get Torque from MegapoundForceInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromPoundForceFeet(QuantityValue? poundforcefeet) + /// If value is NaN or Infinity. + public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) { - return poundforcefeet.HasValue ? FromPoundForceFeet(poundforcefeet.Value) : default(Torque?); + double value = (double) megapoundforceinches; + return new Torque(value, TorqueUnit.MegapoundForceInch); } - /// - /// Get nullable Torque from nullable PoundForceInches. + /// Get Torque from NewtonCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromPoundForceInches(QuantityValue? poundforceinches) + /// If value is NaN or Infinity. + public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) { - return poundforceinches.HasValue ? FromPoundForceInches(poundforceinches.Value) : default(Torque?); + double value = (double) newtoncentimeters; + return new Torque(value, TorqueUnit.NewtonCentimeter); } - /// - /// Get nullable Torque from nullable TonneForceCentimeters. + /// Get Torque from NewtonMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromTonneForceCentimeters(QuantityValue? tonneforcecentimeters) + /// If value is NaN or Infinity. + public static Torque FromNewtonMeters(QuantityValue newtonmeters) { - return tonneforcecentimeters.HasValue ? FromTonneForceCentimeters(tonneforcecentimeters.Value) : default(Torque?); + double value = (double) newtonmeters; + return new Torque(value, TorqueUnit.NewtonMeter); } - /// - /// Get nullable Torque from nullable TonneForceMeters. + /// Get Torque from NewtonMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromTonneForceMeters(QuantityValue? tonneforcemeters) + /// If value is NaN or Infinity. + public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) { - return tonneforcemeters.HasValue ? FromTonneForceMeters(tonneforcemeters.Value) : default(Torque?); + double value = (double) newtonmillimeters; + return new Torque(value, TorqueUnit.NewtonMillimeter); + } + /// + /// Get Torque from PoundForceFeet. + /// + /// If value is NaN or Infinity. + public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) + { + double value = (double) poundforcefeet; + return new Torque(value, TorqueUnit.PoundForceFoot); + } + /// + /// Get Torque from PoundForceInches. + /// + /// If value is NaN or Infinity. + public static Torque FromPoundForceInches(QuantityValue poundforceinches) + { + double value = (double) poundforceinches; + return new Torque(value, TorqueUnit.PoundForceInch); + } + /// + /// Get Torque from TonneForceCentimeters. + /// + /// If value is NaN or Infinity. + public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) + { + double value = (double) tonneforcecentimeters; + return new Torque(value, TorqueUnit.TonneForceCentimeter); + } + /// + /// Get Torque from TonneForceMeters. + /// + /// If value is NaN or Infinity. + public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) + { + double value = (double) tonneforcemeters; + return new Torque(value, TorqueUnit.TonneForceMeter); } - /// - /// Get nullable Torque from nullable TonneForceMillimeters. + /// Get Torque from TonneForceMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Torque? FromTonneForceMillimeters(QuantityValue? tonneforcemillimeters) + /// If value is NaN or Infinity. + public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) { - return tonneforcemillimeters.HasValue ? FromTonneForceMillimeters(tonneforcemillimeters.Value) : default(Torque?); + double value = (double) tonneforcemillimeters; + return new Torque(value, TorqueUnit.TonneForceMillimeter); } /// @@ -257,28 +477,156 @@ public partial struct Torque : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Torque unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Torque? From(QuantityValue? value, TorqueUnit fromUnit) + public static Torque From(QuantityValue value, TorqueUnit fromUnit) { - return value.HasValue ? new Torque((double)value.Value, fromUnit) : default(Torque?); + return new Torque((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static Torque Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Torque Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Torque result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Torque result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static TorqueUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static TorqueUnit ParseUnit(string str, IFormatProvider provider = null) { - provider = provider ?? UnitSystem.DefaultCulture; + return UnitParser.Default.Parse(str, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + public static bool TryParseUnit(string str, out TorqueUnit unit) + { + return TryParseUnit(str, null, out unit); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out TorqueUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Torque operator -(Torque right) @@ -318,6 +666,8 @@ public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] IFormatProvide #endregion + #region Equality / IComparable + public static bool operator <=(Torque left, Torque right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -338,180 +688,256 @@ public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] IFormatProvide return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Torque, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Torque left, Torque right) + public static bool operator ==(Torque left, Torque right) + { + return left.Equals(right); + } + + public static bool operator !=(Torque left, Torque right) + { + return !(left == right); + } + + 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 + public int CompareTo(Torque other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Torque, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Torque left, Torque right) + public override bool Equals(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + if(obj is null || !(obj is Torque objTorque)) + return false; + + return Equals(objTorque); } - #region Parsing + public bool Equals(Torque other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Torque Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Torque other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - TorqueUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromNewtonMeters(x.NewtonMeters + y.NewtonMeters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Torque result) + /// A hash code for the current Torque. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Torque); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TorqueUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Torque to another Torque with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Torque with the specified unit. + public Torque ToUnit(TorqueUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Torque(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TorqueUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case TorqueUnit.KilogramForceCentimeter: return _value*0.0980665019960652; + case TorqueUnit.KilogramForceMeter: return _value*9.80665019960652; + case TorqueUnit.KilogramForceMillimeter: return _value*0.00980665019960652; + case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; + case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; + case TorqueUnit.KilopoundForceFoot: return (_value*1.3558179483314) * 1e3d; + case TorqueUnit.KilopoundForceInch: return (_value*1.129848290276167e-1) * 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; + case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; + case TorqueUnit.MegapoundForceFoot: return (_value*1.3558179483314) * 1e6d; + case TorqueUnit.MegapoundForceInch: return (_value*1.129848290276167e-1) * 1e6d; + case TorqueUnit.NewtonCentimeter: return _value*0.01; + case TorqueUnit.NewtonMeter: return _value; + case TorqueUnit.NewtonMillimeter: return _value*0.001; + case TorqueUnit.PoundForceFoot: return _value*1.3558179483314; + case TorqueUnit.PoundForceInch: return _value*1.129848290276167e-1; + case TorqueUnit.TonneForceCentimeter: return _value*98.0665019960652; + case TorqueUnit.TonneForceMeter: return _value*9806.65019960653; + case TorqueUnit.TonneForceMillimeter: return _value*9.80665019960652; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(TorqueUnit unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); - if (unit == TorqueUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TorqueUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case TorqueUnit.KilogramForceCentimeter: return baseUnitValue*10.1971619222242; + case TorqueUnit.KilogramForceMeter: return baseUnitValue*0.101971619222242; + case TorqueUnit.KilogramForceMillimeter: return baseUnitValue*101.971619222242; + case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; + case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; + case TorqueUnit.KilopoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e3d; + case TorqueUnit.KilopoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; + case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; + case TorqueUnit.MegapoundForceFoot: return (baseUnitValue/1.3558179483314) / 1e6d; + case TorqueUnit.MegapoundForceInch: return (baseUnitValue/1.129848290276167e-1) / 1e6d; + case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; + case TorqueUnit.NewtonMeter: return baseUnitValue; + case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; + case TorqueUnit.PoundForceFoot: return baseUnitValue/1.3558179483314; + case TorqueUnit.PoundForceInch: return baseUnitValue/1.129848290276167e-1; + case TorqueUnit.TonneForceCentimeter: return baseUnitValue*0.0101971619222242; + case TorqueUnit.TonneForceMeter: return baseUnitValue*0.000101971619222242; + case TorqueUnit.TonneForceMillimeter: return baseUnitValue*0.101971619222242; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(TorqueUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs index 8f65da016e..e27bca2e83 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,24 +49,146 @@ namespace UnitsNet /// /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct VitaminA : IComparable, IComparable + public partial struct VitaminA : IQuantity, IEquatable, IComparable, IComparable { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VitaminAUnit? _unit; + + static VitaminA() + { + BaseDimensions = BaseDimensions.Dimensionless; + } + + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public VitaminA(double numericValue, VitaminAUnit unit) + { + if(unit == VitaminAUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; + } + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. + /// + public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; + + /// + /// Represents the largest possible value of VitaminA + /// + public static VitaminA MaxValue => new VitaminA(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of VitaminA + /// + public static VitaminA MinValue => new VitaminA(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.VitaminA; + + /// + /// All units of measurement for the VitaminA quantity. + /// + public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. + /// + public static VitaminA Zero => new VitaminA(0, BaseUnit); + + #endregion + + #region Properties + /// /// The numeric value this quantity was constructed with. /// public double Value => _value; - #region Nullable From Methods + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VitaminA.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VitaminA.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VitaminA in InternationalUnits. + /// + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VitaminAUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] IFormatProvider provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods /// - /// Get nullable VitaminA from nullable InternationalUnits. + /// Get VitaminA from InternationalUnits. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VitaminA? FromInternationalUnits(QuantityValue? internationalunits) + /// If value is NaN or Infinity. + public static VitaminA FromInternationalUnits(QuantityValue internationalunits) { - return internationalunits.HasValue ? FromInternationalUnits(internationalunits.Value) : default(VitaminA?); + double value = (double) internationalunits; + return new VitaminA(value, VitaminAUnit.InternationalUnit); } /// @@ -77,28 +197,156 @@ public partial struct VitaminA : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// VitaminA unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VitaminA? From(QuantityValue? value, VitaminAUnit fromUnit) + public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) { - return value.HasValue ? new VitaminA((double)value.Value, fromUnit) : default(VitaminA?); + return new VitaminA((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static VitaminA Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VitaminA result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VitaminA result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static VitaminAUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static VitaminAUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VitaminAUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out VitaminAUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static VitaminA operator -(VitaminA right) @@ -138,6 +386,8 @@ public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] IFormatProvi #endregion + #region Equality / IComparable + public static bool operator <=(VitaminA left, VitaminA right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -158,180 +408,216 @@ public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] IFormatProvi return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VitaminA, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(VitaminA left, VitaminA right) + public static bool operator ==(VitaminA left, VitaminA right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return left.Equals(right); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VitaminA, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(VitaminA left, VitaminA right) + public static bool operator !=(VitaminA left, VitaminA right) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return !(left == right); } - #region Parsing + 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 + public int CompareTo(VitaminA other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VitaminA Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VitaminAUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromInternationalUnits(x.InternationalUnits + y.InternationalUnits)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VitaminA result) + /// A hash code for the current VitaminA. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(VitaminA); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VitaminAUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this VitaminA to another VitaminA with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A VitaminA with the specified unit. + public VitaminA ToUnit(VitaminAUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new VitaminA(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VitaminAUnit ParseUnit(string str, IFormatProvider provider = null) + /// 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 (str == null) throw new ArgumentNullException(nameof(str)); + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == VitaminAUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VitaminAUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case VitaminAUnit.InternationalUnit: return baseUnitValue; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(VitaminAUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs index 7c3d4a7071..5dfddc94db 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,420 +49,734 @@ namespace UnitsNet /// /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct Volume : IComparable, IComparable + public partial struct Volume : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable Volume from nullable AuTablespoons. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromAuTablespoons(QuantityValue? autablespoons) + private readonly VolumeUnit? _unit; + + static Volume() { - return autablespoons.HasValue ? FromAuTablespoons(autablespoons.Value) : default(Volume?); + BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); } /// - /// Get nullable Volume from nullable Centiliters. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCentiliters(QuantityValue? centiliters) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public Volume(double numericValue, VolumeUnit unit) { - return centiliters.HasValue ? FromCentiliters(centiliters.Value) : default(Volume?); + if(unit == VolumeUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of Volume, which is CubicMeter. All conversions go via this value. + /// + public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; + + /// + /// Represents the largest possible value of Volume + /// + public static Volume MaxValue => new Volume(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Volume + /// + public static Volume MinValue => new Volume(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.Volume; + /// - /// Get nullable Volume from nullable CubicCentimeters. + /// All units of measurement for the Volume quantity. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicCentimeters(QuantityValue? cubiccentimeters) + public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. + /// + public static Volume Zero => new Volume(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => Volume.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => Volume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get Volume in AuTablespoons. + /// + public double AuTablespoons => As(VolumeUnit.AuTablespoon); + + /// + /// Get Volume in Centiliters. + /// + public double Centiliters => As(VolumeUnit.Centiliter); + + /// + /// Get Volume in CubicCentimeters. + /// + public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); + + /// + /// Get Volume in CubicDecimeters. + /// + public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); + + /// + /// Get Volume in CubicFeet. + /// + public double CubicFeet => As(VolumeUnit.CubicFoot); + + /// + /// Get Volume in CubicInches. + /// + public double CubicInches => As(VolumeUnit.CubicInch); + + /// + /// Get Volume in CubicKilometers. + /// + public double CubicKilometers => As(VolumeUnit.CubicKilometer); + + /// + /// Get Volume in CubicMeters. + /// + public double CubicMeters => As(VolumeUnit.CubicMeter); + + /// + /// Get Volume in CubicMicrometers. + /// + public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); + + /// + /// Get Volume in CubicMiles. + /// + public double CubicMiles => As(VolumeUnit.CubicMile); + + /// + /// Get Volume in CubicMillimeters. + /// + public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); + + /// + /// Get Volume in CubicYards. + /// + public double CubicYards => As(VolumeUnit.CubicYard); + + /// + /// Get Volume in Deciliters. + /// + public double Deciliters => As(VolumeUnit.Deciliter); + + /// + /// Get Volume in HectocubicFeet. + /// + public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); + + /// + /// Get Volume in HectocubicMeters. + /// + public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); + + /// + /// Get Volume in Hectoliters. + /// + public double Hectoliters => As(VolumeUnit.Hectoliter); + + /// + /// Get Volume in ImperialBeerBarrels. + /// + public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); + + /// + /// Get Volume in ImperialGallons. + /// + public double ImperialGallons => As(VolumeUnit.ImperialGallon); + + /// + /// Get Volume in ImperialOunces. + /// + public double ImperialOunces => As(VolumeUnit.ImperialOunce); + + /// + /// Get Volume in KilocubicFeet. + /// + public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); + + /// + /// Get Volume in KilocubicMeters. + /// + public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); + + /// + /// Get Volume in KiloimperialGallons. + /// + public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); + + /// + /// Get Volume in Kiloliters. + /// + public double Kiloliters => As(VolumeUnit.Kiloliter); + + /// + /// Get Volume in KilousGallons. + /// + public double KilousGallons => As(VolumeUnit.KilousGallon); + + /// + /// Get Volume in Liters. + /// + public double Liters => As(VolumeUnit.Liter); + + /// + /// Get Volume in MegacubicFeet. + /// + public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); + + /// + /// Get Volume in MegaimperialGallons. + /// + public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); + + /// + /// Get Volume in MegausGallons. + /// + public double MegausGallons => As(VolumeUnit.MegausGallon); + + /// + /// Get Volume in MetricCups. + /// + public double MetricCups => As(VolumeUnit.MetricCup); + + /// + /// Get Volume in MetricTeaspoons. + /// + public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); + + /// + /// Get Volume in Microliters. + /// + public double Microliters => As(VolumeUnit.Microliter); + + /// + /// Get Volume in Milliliters. + /// + public double Milliliters => As(VolumeUnit.Milliliter); + + /// + /// Get Volume in OilBarrels. + /// + public double OilBarrels => As(VolumeUnit.OilBarrel); + + /// + /// Get Volume in UkTablespoons. + /// + public double UkTablespoons => As(VolumeUnit.UkTablespoon); + + /// + /// Get Volume in UsBeerBarrels. + /// + public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); + + /// + /// Get Volume in UsCustomaryCups. + /// + public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); + + /// + /// Get Volume in UsGallons. + /// + public double UsGallons => As(VolumeUnit.UsGallon); + + /// + /// Get Volume in UsLegalCups. + /// + public double UsLegalCups => As(VolumeUnit.UsLegalCup); + + /// + /// Get Volume in UsOunces. + /// + public double UsOunces => As(VolumeUnit.UsOunce); + + /// + /// Get Volume in UsPints. + /// + public double UsPints => As(VolumeUnit.UsPint); + + /// + /// Get Volume in UsQuarts. + /// + public double UsQuarts => As(VolumeUnit.UsQuart); + + /// + /// Get Volume in UsTablespoons. + /// + public double UsTablespoons => As(VolumeUnit.UsTablespoon); + + /// + /// Get Volume in UsTeaspoons. + /// + public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeUnit unit) { - return cubiccentimeters.HasValue ? FromCubicCentimeters(cubiccentimeters.Value) : default(Volume?); + return GetAbbreviation(unit, null); } /// - /// Get nullable Volume from nullable CubicDecimeters. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicDecimeters(QuantityValue? cubicdecimeters) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] IFormatProvider provider) { - return cubicdecimeters.HasValue ? FromCubicDecimeters(cubicdecimeters.Value) : default(Volume?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable Volume from nullable CubicFeet. + /// Get Volume from AuTablespoons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicFeet(QuantityValue? cubicfeet) + /// If value is NaN or Infinity. + public static Volume FromAuTablespoons(QuantityValue autablespoons) { - return cubicfeet.HasValue ? FromCubicFeet(cubicfeet.Value) : default(Volume?); + double value = (double) autablespoons; + return new Volume(value, VolumeUnit.AuTablespoon); } - /// - /// Get nullable Volume from nullable CubicInches. + /// Get Volume from Centiliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicInches(QuantityValue? cubicinches) + /// If value is NaN or Infinity. + public static Volume FromCentiliters(QuantityValue centiliters) { - return cubicinches.HasValue ? FromCubicInches(cubicinches.Value) : default(Volume?); + double value = (double) centiliters; + return new Volume(value, VolumeUnit.Centiliter); } - /// - /// Get nullable Volume from nullable CubicKilometers. + /// Get Volume from CubicCentimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicKilometers(QuantityValue? cubickilometers) + /// If value is NaN or Infinity. + public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) { - return cubickilometers.HasValue ? FromCubicKilometers(cubickilometers.Value) : default(Volume?); + double value = (double) cubiccentimeters; + return new Volume(value, VolumeUnit.CubicCentimeter); } - /// - /// Get nullable Volume from nullable CubicMeters. + /// Get Volume from CubicDecimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicMeters(QuantityValue? cubicmeters) + /// If value is NaN or Infinity. + public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) { - return cubicmeters.HasValue ? FromCubicMeters(cubicmeters.Value) : default(Volume?); + double value = (double) cubicdecimeters; + return new Volume(value, VolumeUnit.CubicDecimeter); } - /// - /// Get nullable Volume from nullable CubicMicrometers. + /// Get Volume from CubicFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicMicrometers(QuantityValue? cubicmicrometers) + /// If value is NaN or Infinity. + public static Volume FromCubicFeet(QuantityValue cubicfeet) { - return cubicmicrometers.HasValue ? FromCubicMicrometers(cubicmicrometers.Value) : default(Volume?); + double value = (double) cubicfeet; + return new Volume(value, VolumeUnit.CubicFoot); } - /// - /// Get nullable Volume from nullable CubicMiles. + /// Get Volume from CubicInches. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicMiles(QuantityValue? cubicmiles) + /// If value is NaN or Infinity. + public static Volume FromCubicInches(QuantityValue cubicinches) { - return cubicmiles.HasValue ? FromCubicMiles(cubicmiles.Value) : default(Volume?); + double value = (double) cubicinches; + return new Volume(value, VolumeUnit.CubicInch); } - /// - /// Get nullable Volume from nullable CubicMillimeters. + /// Get Volume from CubicKilometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicMillimeters(QuantityValue? cubicmillimeters) + /// If value is NaN or Infinity. + public static Volume FromCubicKilometers(QuantityValue cubickilometers) { - return cubicmillimeters.HasValue ? FromCubicMillimeters(cubicmillimeters.Value) : default(Volume?); + double value = (double) cubickilometers; + return new Volume(value, VolumeUnit.CubicKilometer); } - /// - /// Get nullable Volume from nullable CubicYards. + /// Get Volume from CubicMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromCubicYards(QuantityValue? cubicyards) + /// If value is NaN or Infinity. + public static Volume FromCubicMeters(QuantityValue cubicmeters) { - return cubicyards.HasValue ? FromCubicYards(cubicyards.Value) : default(Volume?); + double value = (double) cubicmeters; + return new Volume(value, VolumeUnit.CubicMeter); } - /// - /// Get nullable Volume from nullable Deciliters. + /// Get Volume from CubicMicrometers. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromDeciliters(QuantityValue? deciliters) + /// If value is NaN or Infinity. + public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) { - return deciliters.HasValue ? FromDeciliters(deciliters.Value) : default(Volume?); + double value = (double) cubicmicrometers; + return new Volume(value, VolumeUnit.CubicMicrometer); } - /// - /// Get nullable Volume from nullable HectocubicFeet. + /// Get Volume from CubicMiles. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromHectocubicFeet(QuantityValue? hectocubicfeet) + /// If value is NaN or Infinity. + public static Volume FromCubicMiles(QuantityValue cubicmiles) { - return hectocubicfeet.HasValue ? FromHectocubicFeet(hectocubicfeet.Value) : default(Volume?); + double value = (double) cubicmiles; + return new Volume(value, VolumeUnit.CubicMile); } - /// - /// Get nullable Volume from nullable HectocubicMeters. + /// Get Volume from CubicMillimeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromHectocubicMeters(QuantityValue? hectocubicmeters) + /// If value is NaN or Infinity. + public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) { - return hectocubicmeters.HasValue ? FromHectocubicMeters(hectocubicmeters.Value) : default(Volume?); + double value = (double) cubicmillimeters; + return new Volume(value, VolumeUnit.CubicMillimeter); } - /// - /// Get nullable Volume from nullable Hectoliters. + /// Get Volume from CubicYards. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromHectoliters(QuantityValue? hectoliters) + /// If value is NaN or Infinity. + public static Volume FromCubicYards(QuantityValue cubicyards) { - return hectoliters.HasValue ? FromHectoliters(hectoliters.Value) : default(Volume?); + double value = (double) cubicyards; + return new Volume(value, VolumeUnit.CubicYard); } - /// - /// Get nullable Volume from nullable ImperialBeerBarrels. + /// Get Volume from Deciliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromImperialBeerBarrels(QuantityValue? imperialbeerbarrels) + /// If value is NaN or Infinity. + public static Volume FromDeciliters(QuantityValue deciliters) { - return imperialbeerbarrels.HasValue ? FromImperialBeerBarrels(imperialbeerbarrels.Value) : default(Volume?); + double value = (double) deciliters; + return new Volume(value, VolumeUnit.Deciliter); } - /// - /// Get nullable Volume from nullable ImperialGallons. + /// Get Volume from HectocubicFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromImperialGallons(QuantityValue? imperialgallons) + /// If value is NaN or Infinity. + public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) { - return imperialgallons.HasValue ? FromImperialGallons(imperialgallons.Value) : default(Volume?); + double value = (double) hectocubicfeet; + return new Volume(value, VolumeUnit.HectocubicFoot); } - /// - /// Get nullable Volume from nullable ImperialOunces. + /// Get Volume from HectocubicMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromImperialOunces(QuantityValue? imperialounces) + /// If value is NaN or Infinity. + public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) { - return imperialounces.HasValue ? FromImperialOunces(imperialounces.Value) : default(Volume?); + double value = (double) hectocubicmeters; + return new Volume(value, VolumeUnit.HectocubicMeter); } - /// - /// Get nullable Volume from nullable KilocubicFeet. + /// Get Volume from Hectoliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromKilocubicFeet(QuantityValue? kilocubicfeet) + /// If value is NaN or Infinity. + public static Volume FromHectoliters(QuantityValue hectoliters) { - return kilocubicfeet.HasValue ? FromKilocubicFeet(kilocubicfeet.Value) : default(Volume?); + double value = (double) hectoliters; + return new Volume(value, VolumeUnit.Hectoliter); } - /// - /// Get nullable Volume from nullable KilocubicMeters. + /// Get Volume from ImperialBeerBarrels. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromKilocubicMeters(QuantityValue? kilocubicmeters) + /// If value is NaN or Infinity. + public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) { - return kilocubicmeters.HasValue ? FromKilocubicMeters(kilocubicmeters.Value) : default(Volume?); + double value = (double) imperialbeerbarrels; + return new Volume(value, VolumeUnit.ImperialBeerBarrel); } - /// - /// Get nullable Volume from nullable KiloimperialGallons. + /// Get Volume from ImperialGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromKiloimperialGallons(QuantityValue? kiloimperialgallons) + /// If value is NaN or Infinity. + public static Volume FromImperialGallons(QuantityValue imperialgallons) { - return kiloimperialgallons.HasValue ? FromKiloimperialGallons(kiloimperialgallons.Value) : default(Volume?); + double value = (double) imperialgallons; + return new Volume(value, VolumeUnit.ImperialGallon); } - /// - /// Get nullable Volume from nullable Kiloliters. + /// Get Volume from ImperialOunces. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromKiloliters(QuantityValue? kiloliters) + /// If value is NaN or Infinity. + public static Volume FromImperialOunces(QuantityValue imperialounces) { - return kiloliters.HasValue ? FromKiloliters(kiloliters.Value) : default(Volume?); + double value = (double) imperialounces; + return new Volume(value, VolumeUnit.ImperialOunce); } - /// - /// Get nullable Volume from nullable KilousGallons. + /// Get Volume from KilocubicFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromKilousGallons(QuantityValue? kilousgallons) + /// If value is NaN or Infinity. + public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) { - return kilousgallons.HasValue ? FromKilousGallons(kilousgallons.Value) : default(Volume?); + double value = (double) kilocubicfeet; + return new Volume(value, VolumeUnit.KilocubicFoot); } - /// - /// Get nullable Volume from nullable Liters. + /// Get Volume from KilocubicMeters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromLiters(QuantityValue? liters) + /// If value is NaN or Infinity. + public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) { - return liters.HasValue ? FromLiters(liters.Value) : default(Volume?); + double value = (double) kilocubicmeters; + return new Volume(value, VolumeUnit.KilocubicMeter); } - /// - /// Get nullable Volume from nullable MegacubicFeet. + /// Get Volume from KiloimperialGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMegacubicFeet(QuantityValue? megacubicfeet) + /// If value is NaN or Infinity. + public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) { - return megacubicfeet.HasValue ? FromMegacubicFeet(megacubicfeet.Value) : default(Volume?); + double value = (double) kiloimperialgallons; + return new Volume(value, VolumeUnit.KiloimperialGallon); } - /// - /// Get nullable Volume from nullable MegaimperialGallons. + /// Get Volume from Kiloliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMegaimperialGallons(QuantityValue? megaimperialgallons) + /// If value is NaN or Infinity. + public static Volume FromKiloliters(QuantityValue kiloliters) { - return megaimperialgallons.HasValue ? FromMegaimperialGallons(megaimperialgallons.Value) : default(Volume?); + double value = (double) kiloliters; + return new Volume(value, VolumeUnit.Kiloliter); } - /// - /// Get nullable Volume from nullable MegausGallons. + /// Get Volume from KilousGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMegausGallons(QuantityValue? megausgallons) + /// If value is NaN or Infinity. + public static Volume FromKilousGallons(QuantityValue kilousgallons) { - return megausgallons.HasValue ? FromMegausGallons(megausgallons.Value) : default(Volume?); + double value = (double) kilousgallons; + return new Volume(value, VolumeUnit.KilousGallon); } - /// - /// Get nullable Volume from nullable MetricCups. + /// Get Volume from Liters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMetricCups(QuantityValue? metriccups) + /// If value is NaN or Infinity. + public static Volume FromLiters(QuantityValue liters) { - return metriccups.HasValue ? FromMetricCups(metriccups.Value) : default(Volume?); + double value = (double) liters; + return new Volume(value, VolumeUnit.Liter); } - /// - /// Get nullable Volume from nullable MetricTeaspoons. + /// Get Volume from MegacubicFeet. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMetricTeaspoons(QuantityValue? metricteaspoons) + /// If value is NaN or Infinity. + public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) { - return metricteaspoons.HasValue ? FromMetricTeaspoons(metricteaspoons.Value) : default(Volume?); + double value = (double) megacubicfeet; + return new Volume(value, VolumeUnit.MegacubicFoot); } - /// - /// Get nullable Volume from nullable Microliters. + /// Get Volume from MegaimperialGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMicroliters(QuantityValue? microliters) + /// If value is NaN or Infinity. + public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) { - return microliters.HasValue ? FromMicroliters(microliters.Value) : default(Volume?); + double value = (double) megaimperialgallons; + return new Volume(value, VolumeUnit.MegaimperialGallon); } - /// - /// Get nullable Volume from nullable Milliliters. + /// Get Volume from MegausGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromMilliliters(QuantityValue? milliliters) + /// If value is NaN or Infinity. + public static Volume FromMegausGallons(QuantityValue megausgallons) { - return milliliters.HasValue ? FromMilliliters(milliliters.Value) : default(Volume?); + double value = (double) megausgallons; + return new Volume(value, VolumeUnit.MegausGallon); } - /// - /// Get nullable Volume from nullable OilBarrels. + /// Get Volume from MetricCups. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromOilBarrels(QuantityValue? oilbarrels) + /// If value is NaN or Infinity. + public static Volume FromMetricCups(QuantityValue metriccups) { - return oilbarrels.HasValue ? FromOilBarrels(oilbarrels.Value) : default(Volume?); + double value = (double) metriccups; + return new Volume(value, VolumeUnit.MetricCup); } - /// - /// Get nullable Volume from nullable Tablespoons. + /// Get Volume from MetricTeaspoons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromTablespoons(QuantityValue? tablespoons) + /// If value is NaN or Infinity. + public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) { - return tablespoons.HasValue ? FromTablespoons(tablespoons.Value) : default(Volume?); + double value = (double) metricteaspoons; + return new Volume(value, VolumeUnit.MetricTeaspoon); } - /// - /// Get nullable Volume from nullable Teaspoons. + /// Get Volume from Microliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromTeaspoons(QuantityValue? teaspoons) + /// If value is NaN or Infinity. + public static Volume FromMicroliters(QuantityValue microliters) { - return teaspoons.HasValue ? FromTeaspoons(teaspoons.Value) : default(Volume?); + double value = (double) microliters; + return new Volume(value, VolumeUnit.Microliter); } - /// - /// Get nullable Volume from nullable UkTablespoons. + /// Get Volume from Milliliters. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUkTablespoons(QuantityValue? uktablespoons) + /// If value is NaN or Infinity. + public static Volume FromMilliliters(QuantityValue milliliters) { - return uktablespoons.HasValue ? FromUkTablespoons(uktablespoons.Value) : default(Volume?); + double value = (double) milliliters; + return new Volume(value, VolumeUnit.Milliliter); } - /// - /// Get nullable Volume from nullable UsBeerBarrels. + /// Get Volume from OilBarrels. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsBeerBarrels(QuantityValue? usbeerbarrels) + /// If value is NaN or Infinity. + public static Volume FromOilBarrels(QuantityValue oilbarrels) { - return usbeerbarrels.HasValue ? FromUsBeerBarrels(usbeerbarrels.Value) : default(Volume?); + double value = (double) oilbarrels; + return new Volume(value, VolumeUnit.OilBarrel); } - /// - /// Get nullable Volume from nullable UsCustomaryCups. + /// Get Volume from UkTablespoons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsCustomaryCups(QuantityValue? uscustomarycups) + /// If value is NaN or Infinity. + public static Volume FromUkTablespoons(QuantityValue uktablespoons) { - return uscustomarycups.HasValue ? FromUsCustomaryCups(uscustomarycups.Value) : default(Volume?); + double value = (double) uktablespoons; + return new Volume(value, VolumeUnit.UkTablespoon); } - /// - /// Get nullable Volume from nullable UsGallons. + /// Get Volume from UsBeerBarrels. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsGallons(QuantityValue? usgallons) + /// If value is NaN or Infinity. + public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) { - return usgallons.HasValue ? FromUsGallons(usgallons.Value) : default(Volume?); + double value = (double) usbeerbarrels; + return new Volume(value, VolumeUnit.UsBeerBarrel); } - /// - /// Get nullable Volume from nullable UsLegalCups. + /// Get Volume from UsCustomaryCups. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsLegalCups(QuantityValue? uslegalcups) + /// If value is NaN or Infinity. + public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) { - return uslegalcups.HasValue ? FromUsLegalCups(uslegalcups.Value) : default(Volume?); + double value = (double) uscustomarycups; + return new Volume(value, VolumeUnit.UsCustomaryCup); } - /// - /// Get nullable Volume from nullable UsOunces. + /// Get Volume from UsGallons. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsOunces(QuantityValue? usounces) + /// If value is NaN or Infinity. + public static Volume FromUsGallons(QuantityValue usgallons) { - return usounces.HasValue ? FromUsOunces(usounces.Value) : default(Volume?); + double value = (double) usgallons; + return new Volume(value, VolumeUnit.UsGallon); } - /// - /// Get nullable Volume from nullable UsPints. + /// Get Volume from UsLegalCups. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsPints(QuantityValue? uspints) + /// If value is NaN or Infinity. + public static Volume FromUsLegalCups(QuantityValue uslegalcups) { - return uspints.HasValue ? FromUsPints(uspints.Value) : default(Volume?); + double value = (double) uslegalcups; + return new Volume(value, VolumeUnit.UsLegalCup); } - /// - /// Get nullable Volume from nullable UsQuarts. + /// Get Volume from UsOunces. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsQuarts(QuantityValue? usquarts) + /// If value is NaN or Infinity. + public static Volume FromUsOunces(QuantityValue usounces) { - return usquarts.HasValue ? FromUsQuarts(usquarts.Value) : default(Volume?); + double value = (double) usounces; + return new Volume(value, VolumeUnit.UsOunce); } - /// - /// Get nullable Volume from nullable UsTablespoons. + /// Get Volume from UsPints. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsTablespoons(QuantityValue? ustablespoons) + /// If value is NaN or Infinity. + public static Volume FromUsPints(QuantityValue uspints) { - return ustablespoons.HasValue ? FromUsTablespoons(ustablespoons.Value) : default(Volume?); + double value = (double) uspints; + return new Volume(value, VolumeUnit.UsPint); } - /// - /// Get nullable Volume from nullable UsTeaspoons. + /// Get Volume from UsQuarts. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static Volume? FromUsTeaspoons(QuantityValue? usteaspoons) + /// If value is NaN or Infinity. + public static Volume FromUsQuarts(QuantityValue usquarts) { - return usteaspoons.HasValue ? FromUsTeaspoons(usteaspoons.Value) : default(Volume?); + double value = (double) usquarts; + return new Volume(value, VolumeUnit.UsQuart); + } + /// + /// Get Volume from UsTablespoons. + /// + /// If value is NaN or Infinity. + public static Volume FromUsTablespoons(QuantityValue ustablespoons) + { + double value = (double) ustablespoons; + return new Volume(value, VolumeUnit.UsTablespoon); + } + /// + /// Get Volume from UsTeaspoons. + /// + /// If value is NaN or Infinity. + public static Volume FromUsTeaspoons(QuantityValue usteaspoons) + { + double value = (double) usteaspoons; + return new Volume(value, VolumeUnit.UsTeaspoon); } /// @@ -473,28 +785,156 @@ public partial struct Volume : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// Volume unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static Volume? From(QuantityValue? value, VolumeUnit fromUnit) + public static Volume From(QuantityValue value, VolumeUnit fromUnit) { - return value.HasValue ? new Volume((double)value.Value, fromUnit) : default(Volume?); + return new Volume((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static Volume Parse(string str) + { + return Parse(str, null); + } + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static Volume Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out Volume result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Volume result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static VolumeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static VolumeUnit ParseUnit(string str, IFormatProvider provider = null) { - provider = provider ?? UnitSystem.DefaultCulture; + return UnitParser.Default.Parse(str, provider); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + public static bool TryParseUnit(string str, out VolumeUnit unit) + { + return TryParseUnit(str, null, out unit); } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out VolumeUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static Volume operator -(Volume right) @@ -534,6 +974,8 @@ public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] IFormatProvide #endregion + #region Equality / IComparable + public static bool operator <=(Volume left, Volume right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -554,180 +996,300 @@ public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] IFormatProvide return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Volume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(Volume left, Volume right) + public static bool operator ==(Volume left, Volume right) + { + return left.Equals(right); + } + + public static bool operator !=(Volume left, Volume right) + { + return !(left == right); + } + + 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 + public int CompareTo(Volume other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(Volume, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(Volume left, Volume right) + public override bool Equals(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + if(obj is null || !(obj is Volume objVolume)) + return false; + + return Equals(objVolume); } - #region Parsing + public bool Equals(Volume other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Volume Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(Volume other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VolumeUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMeters(x.CubicMeters + y.CubicMeters)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Volume result) + /// A hash code for the current Volume. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(Volume); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this Volume to another Volume with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A Volume with the specified unit. + public Volume ToUnit(VolumeUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new Volume(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case VolumeUnit.AuTablespoon: return _value*2e-5; + case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; + case VolumeUnit.CubicCentimeter: return _value/1e6; + case VolumeUnit.CubicDecimeter: return _value/1e3; + case VolumeUnit.CubicFoot: return _value*0.0283168; + case VolumeUnit.CubicInch: return _value*1.6387*1e-5; + case VolumeUnit.CubicKilometer: return _value*1e9; + case VolumeUnit.CubicMeter: return _value; + case VolumeUnit.CubicMicrometer: return _value/1e18; + case VolumeUnit.CubicMile: return _value*4.16818182544058e9; + case VolumeUnit.CubicMillimeter: return _value/1e9; + case VolumeUnit.CubicYard: return _value*0.764554858; + case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; + case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; + case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; + case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; + case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; + case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; + case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; + case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; + case VolumeUnit.Kiloliter: return (_value/1e3) * 1e3d; + case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; + case VolumeUnit.Liter: return _value/1e3; + case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; + case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; + case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; + case VolumeUnit.MetricCup: return _value*0.00025; + case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; + case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; + case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; + case VolumeUnit.OilBarrel: return _value*0.158987294928; + case VolumeUnit.UkTablespoon: return _value*1.5e-5; + case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; + case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; + case VolumeUnit.UsGallon: return _value*0.00378541; + case VolumeUnit.UsLegalCup: return _value*0.00024; + case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; + case VolumeUnit.UsPint: return _value*4.73176473e-4; + case VolumeUnit.UsQuart: return _value*9.46352946e-4; + case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + private double AsBaseNumericType(VolumeUnit unit) + { + if(Unit == unit) + return _value; - if (unit == VolumeUnit.Undefined) + var baseUnitValue = AsBaseUnit(); + + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; + case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; + case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; + case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; + case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; + case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); + case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; + case VolumeUnit.CubicMeter: return baseUnitValue; + case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; + case VolumeUnit.CubicMile: return baseUnitValue/4.16818182544058e9; + case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; + case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; + case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; + case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; + case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; + case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; + case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; + case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; + case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; + case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; + case VolumeUnit.Kiloliter: return (baseUnitValue*1e3) / 1e3d; + case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; + case VolumeUnit.Liter: return baseUnitValue*1e3; + case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; + case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; + case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; + case VolumeUnit.MetricCup: return baseUnitValue/0.00025; + case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; + case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; + case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; + case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; + case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; + case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; + case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; + case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; + case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; + case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; + case VolumeUnit.UsPint: return baseUnitValue/4.73176473e-4; + case VolumeUnit.UsQuart: return baseUnitValue/9.46352946e-4; + case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(VolumeUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs index 038ef7cb9f..d5b8346283 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.NetFramework.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -37,12 +36,11 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace @@ -51,267 +49,524 @@ namespace UnitsNet /// /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct VolumeFlow : IComparable, IComparable + public partial struct VolumeFlow : IQuantity, IEquatable, IComparable, IComparable { /// /// The numeric value this quantity was constructed with. /// - public double Value => _value; - - #region Nullable From Methods + private readonly double _value; /// - /// Get nullable VolumeFlow from nullable CentilitersPerMinute. + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCentilitersPerMinute(QuantityValue? centilitersperminute) + private readonly VolumeFlowUnit? _unit; + + static VolumeFlow() { - return centilitersperminute.HasValue ? FromCentilitersPerMinute(centilitersperminute.Value) : default(VolumeFlow?); + BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); } /// - /// Get nullable VolumeFlow from nullable CubicDecimetersPerMinute. + /// Creates the quantity with the given numeric value and unit. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicDecimetersPerMinute(QuantityValue? cubicdecimetersperminute) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + public VolumeFlow(double numericValue, VolumeFlowUnit unit) { - return cubicdecimetersperminute.HasValue ? FromCubicDecimetersPerMinute(cubicdecimetersperminute.Value) : default(VolumeFlow?); + if(unit == VolumeFlowUnit.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); + + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); + _unit = unit; } + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. + /// + public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; + + /// + /// Represents the largest possible value of VolumeFlow + /// + public static VolumeFlow MaxValue => new VolumeFlow(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of VolumeFlow + /// + public static VolumeFlow MinValue => new VolumeFlow(double.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.VolumeFlow; + + /// + /// All units of measurement for the VolumeFlow quantity. + /// + public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// + public static VolumeFlow Zero => new VolumeFlow(0, BaseUnit); + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => VolumeFlow.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// + /// Get VolumeFlow in CentilitersPerMinute. + /// + public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); + + /// + /// Get VolumeFlow in CubicDecimetersPerMinute. + /// + public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); + + /// + /// Get VolumeFlow in CubicFeetPerHour. + /// + public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); + + /// + /// Get VolumeFlow in CubicFeetPerMinute. + /// + public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); + + /// + /// Get VolumeFlow in CubicFeetPerSecond. + /// + public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); + + /// + /// Get VolumeFlow in CubicMetersPerHour. + /// + public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); + + /// + /// Get VolumeFlow in CubicMetersPerMinute. + /// + public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); + + /// + /// Get VolumeFlow in CubicMetersPerSecond. + /// + public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); + + /// + /// Get VolumeFlow in CubicMillimetersPerSecond. + /// + public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); + + /// + /// Get VolumeFlow in CubicYardsPerHour. + /// + public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); + + /// + /// Get VolumeFlow in CubicYardsPerMinute. + /// + public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); + + /// + /// Get VolumeFlow in CubicYardsPerSecond. + /// + public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); + + /// + /// Get VolumeFlow in DecilitersPerMinute. + /// + public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); + + /// + /// Get VolumeFlow in KilolitersPerMinute. + /// + public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); + + /// + /// Get VolumeFlow in KilousGallonsPerMinute. + /// + public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonsPerMinute); + + /// + /// Get VolumeFlow in LitersPerHour. + /// + public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); + /// - /// Get nullable VolumeFlow from nullable CubicFeetPerHour. + /// Get VolumeFlow in LitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicFeetPerHour(QuantityValue? cubicfeetperhour) + public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); + + /// + /// Get VolumeFlow in LitersPerSecond. + /// + public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); + + /// + /// Get VolumeFlow in MicrolitersPerMinute. + /// + public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); + + /// + /// Get VolumeFlow in MillilitersPerMinute. + /// + public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); + + /// + /// Get VolumeFlow in MillionUsGallonsPerDay. + /// + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); + + /// + /// Get VolumeFlow in NanolitersPerMinute. + /// + public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); + + /// + /// Get VolumeFlow in OilBarrelsPerDay. + /// + public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); + + /// + /// Get VolumeFlow in OilBarrelsPerHour. + /// + public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); + + /// + /// Get VolumeFlow in OilBarrelsPerMinute. + /// + public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); + + /// + /// Get VolumeFlow in UsGallonsPerHour. + /// + public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); + + /// + /// Get VolumeFlow in UsGallonsPerMinute. + /// + public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); + + /// + /// Get VolumeFlow in UsGallonsPerSecond. + /// + public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); + + #endregion + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(VolumeFlowUnit unit) { - return cubicfeetperhour.HasValue ? FromCubicFeetPerHour(cubicfeetperhour.Value) : default(VolumeFlow?); + return GetAbbreviation(unit, null); } /// - /// Get nullable VolumeFlow from nullable CubicFeetPerMinute. + /// Get unit abbreviation string. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicFeetPerMinute(QuantityValue? cubicfeetperminute) + /// Unit to get abbreviation for. + /// Unit abbreviation string. + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider) { - return cubicfeetperminute.HasValue ? FromCubicFeetPerMinute(cubicfeetperminute.Value) : default(VolumeFlow?); + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } + #endregion + + #region Static Factory Methods + /// - /// Get nullable VolumeFlow from nullable CubicFeetPerSecond. + /// Get VolumeFlow from CentilitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicFeetPerSecond(QuantityValue? cubicfeetpersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) { - return cubicfeetpersecond.HasValue ? FromCubicFeetPerSecond(cubicfeetpersecond.Value) : default(VolumeFlow?); + double value = (double) centilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable CubicMetersPerHour. + /// Get VolumeFlow from CubicDecimetersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicMetersPerHour(QuantityValue? cubicmetersperhour) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) { - return cubicmetersperhour.HasValue ? FromCubicMetersPerHour(cubicmetersperhour.Value) : default(VolumeFlow?); + double value = (double) cubicdecimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable CubicMetersPerMinute. + /// Get VolumeFlow from CubicFeetPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicMetersPerMinute(QuantityValue? cubicmetersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) { - return cubicmetersperminute.HasValue ? FromCubicMetersPerMinute(cubicmetersperminute.Value) : default(VolumeFlow?); + double value = (double) cubicfeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); } - /// - /// Get nullable VolumeFlow from nullable CubicMetersPerSecond. + /// Get VolumeFlow from CubicFeetPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicMetersPerSecond(QuantityValue? cubicmeterspersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) { - return cubicmeterspersecond.HasValue ? FromCubicMetersPerSecond(cubicmeterspersecond.Value) : default(VolumeFlow?); + double value = (double) cubicfeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); } - /// - /// Get nullable VolumeFlow from nullable CubicMillimetersPerSecond. + /// Get VolumeFlow from CubicFeetPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicMillimetersPerSecond(QuantityValue? cubicmillimeterspersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) { - return cubicmillimeterspersecond.HasValue ? FromCubicMillimetersPerSecond(cubicmillimeterspersecond.Value) : default(VolumeFlow?); + double value = (double) cubicfeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); } - /// - /// Get nullable VolumeFlow from nullable CubicYardsPerHour. + /// Get VolumeFlow from CubicMetersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicYardsPerHour(QuantityValue? cubicyardsperhour) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) { - return cubicyardsperhour.HasValue ? FromCubicYardsPerHour(cubicyardsperhour.Value) : default(VolumeFlow?); + double value = (double) cubicmetersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); } - /// - /// Get nullable VolumeFlow from nullable CubicYardsPerMinute. + /// Get VolumeFlow from CubicMetersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicYardsPerMinute(QuantityValue? cubicyardsperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) { - return cubicyardsperminute.HasValue ? FromCubicYardsPerMinute(cubicyardsperminute.Value) : default(VolumeFlow?); + double value = (double) cubicmetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable CubicYardsPerSecond. + /// Get VolumeFlow from CubicMetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromCubicYardsPerSecond(QuantityValue? cubicyardspersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) { - return cubicyardspersecond.HasValue ? FromCubicYardsPerSecond(cubicyardspersecond.Value) : default(VolumeFlow?); + double value = (double) cubicmeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); } - /// - /// Get nullable VolumeFlow from nullable DecilitersPerMinute. + /// Get VolumeFlow from CubicMillimetersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromDecilitersPerMinute(QuantityValue? decilitersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue cubicmillimeterspersecond) { - return decilitersperminute.HasValue ? FromDecilitersPerMinute(decilitersperminute.Value) : default(VolumeFlow?); + double value = (double) cubicmillimeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); } - /// - /// Get nullable VolumeFlow from nullable KilolitersPerMinute. + /// Get VolumeFlow from CubicYardsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromKilolitersPerMinute(QuantityValue? kilolitersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) { - return kilolitersperminute.HasValue ? FromKilolitersPerMinute(kilolitersperminute.Value) : default(VolumeFlow?); + double value = (double) cubicyardsperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); } - /// - /// Get nullable VolumeFlow from nullable KilousGallonsPerMinute. + /// Get VolumeFlow from CubicYardsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromKilousGallonsPerMinute(QuantityValue? kilousgallonsperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) { - return kilousgallonsperminute.HasValue ? FromKilousGallonsPerMinute(kilousgallonsperminute.Value) : default(VolumeFlow?); + double value = (double) cubicyardsperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); } - /// - /// Get nullable VolumeFlow from nullable LitersPerHour. + /// Get VolumeFlow from CubicYardsPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromLitersPerHour(QuantityValue? litersperhour) + /// If value is NaN or Infinity. + public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) { - return litersperhour.HasValue ? FromLitersPerHour(litersperhour.Value) : default(VolumeFlow?); + double value = (double) cubicyardspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); } - /// - /// Get nullable VolumeFlow from nullable LitersPerMinute. + /// Get VolumeFlow from DecilitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromLitersPerMinute(QuantityValue? litersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) { - return litersperminute.HasValue ? FromLitersPerMinute(litersperminute.Value) : default(VolumeFlow?); + double value = (double) decilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable LitersPerSecond. + /// Get VolumeFlow from KilolitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromLitersPerSecond(QuantityValue? literspersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) { - return literspersecond.HasValue ? FromLitersPerSecond(literspersecond.Value) : default(VolumeFlow?); + double value = (double) kilolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable MicrolitersPerMinute. + /// Get VolumeFlow from KilousGallonsPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromMicrolitersPerMinute(QuantityValue? microlitersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue kilousgallonsperminute) { - return microlitersperminute.HasValue ? FromMicrolitersPerMinute(microlitersperminute.Value) : default(VolumeFlow?); + double value = (double) kilousgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.KilousGallonsPerMinute); } - /// - /// Get nullable VolumeFlow from nullable MillilitersPerMinute. + /// Get VolumeFlow from LitersPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromMillilitersPerMinute(QuantityValue? millilitersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) { - return millilitersperminute.HasValue ? FromMillilitersPerMinute(millilitersperminute.Value) : default(VolumeFlow?); + double value = (double) litersperhour; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); } - /// - /// Get nullable VolumeFlow from nullable MillionUsGallonsPerDay. + /// Get VolumeFlow from LitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromMillionUsGallonsPerDay(QuantityValue? millionusgallonsperday) + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) { - return millionusgallonsperday.HasValue ? FromMillionUsGallonsPerDay(millionusgallonsperday.Value) : default(VolumeFlow?); + double value = (double) litersperminute; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable NanolitersPerMinute. + /// Get VolumeFlow from LitersPerSecond. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromNanolitersPerMinute(QuantityValue? nanolitersperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) { - return nanolitersperminute.HasValue ? FromNanolitersPerMinute(nanolitersperminute.Value) : default(VolumeFlow?); + double value = (double) literspersecond; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); } - /// - /// Get nullable VolumeFlow from nullable OilBarrelsPerDay. + /// Get VolumeFlow from MicrolitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromOilBarrelsPerDay(QuantityValue? oilbarrelsperday) + /// If value is NaN or Infinity. + public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) { - return oilbarrelsperday.HasValue ? FromOilBarrelsPerDay(oilbarrelsperday.Value) : default(VolumeFlow?); + double value = (double) microlitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable OilBarrelsPerHour. + /// Get VolumeFlow from MillilitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromOilBarrelsPerHour(QuantityValue? oilbarrelsperhour) + /// If value is NaN or Infinity. + public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) { - return oilbarrelsperhour.HasValue ? FromOilBarrelsPerHour(oilbarrelsperhour.Value) : default(VolumeFlow?); + double value = (double) millilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable OilBarrelsPerMinute. + /// Get VolumeFlow from MillionUsGallonsPerDay. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromOilBarrelsPerMinute(QuantityValue? oilbarrelsperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) { - return oilbarrelsperminute.HasValue ? FromOilBarrelsPerMinute(oilbarrelsperminute.Value) : default(VolumeFlow?); + double value = (double) millionusgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); } - /// - /// Get nullable VolumeFlow from nullable UsGallonsPerHour. + /// Get VolumeFlow from NanolitersPerMinute. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromUsGallonsPerHour(QuantityValue? usgallonsperhour) + /// If value is NaN or Infinity. + public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) { - return usgallonsperhour.HasValue ? FromUsGallonsPerHour(usgallonsperhour.Value) : default(VolumeFlow?); + double value = (double) nanolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); } - /// - /// Get nullable VolumeFlow from nullable UsGallonsPerMinute. + /// Get VolumeFlow from OilBarrelsPerDay. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromUsGallonsPerMinute(QuantityValue? usgallonsperminute) + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) { - return usgallonsperminute.HasValue ? FromUsGallonsPerMinute(usgallonsperminute.Value) : default(VolumeFlow?); + double value = (double) oilbarrelsperday; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); } - /// - /// Get nullable VolumeFlow from nullable UsGallonsPerSecond. + /// Get VolumeFlow from OilBarrelsPerHour. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static VolumeFlow? FromUsGallonsPerSecond(QuantityValue? usgallonspersecond) + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) { - return usgallonspersecond.HasValue ? FromUsGallonsPerSecond(usgallonspersecond.Value) : default(VolumeFlow?); + double value = (double) oilbarrelsperhour; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); + } + /// + /// Get VolumeFlow from OilBarrelsPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) + { + double value = (double) oilbarrelsperminute; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerHour. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) + { + double value = (double) usgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); + } + /// + /// Get VolumeFlow from UsGallonsPerMinute. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) + { + double value = (double) usgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); + } + /// + /// Get VolumeFlow from UsGallonsPerSecond. + /// + /// If value is NaN or Infinity. + public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) + { + double value = (double) usgallonspersecond; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); } /// @@ -320,28 +575,156 @@ public partial struct VolumeFlow : IComparable, IComparable /// Value to convert from. /// Unit to convert from. /// VolumeFlow unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static VolumeFlow? From(QuantityValue? value, VolumeFlowUnit fromUnit) + public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) { - return value.HasValue ? new VolumeFlow((double)value.Value, fromUnit) : default(VolumeFlow?); + return new VolumeFlow((double)value, fromUnit); } #endregion + #region Static Parse Methods + /// - /// Get unit abbreviation string. + /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider) + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically 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) { - provider = provider ?? UnitSystem.DefaultCulture; + return Parse(str, null); + } - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static VolumeFlow Parse(string str, [CanBeNull] IFormatProvider provider) + { + return QuantityParser.Default.Parse( + str, + provider, + From); } + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out VolumeFlow result) + { + return TryParse(str, null, out result); + } + + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// True if successful, otherwise false. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VolumeFlow result) + { + return QuantityParser.Default.TryParse( + str, + provider, + From, + out result); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + public static VolumeFlowUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// Error parsing string. + /// Format to use when parsing number and unit. Defaults to if null. + public static VolumeFlowUnit ParseUnit(string str, IFormatProvider provider = null) + { + return UnitParser.Default.Parse(str, provider); + } + + public static bool TryParseUnit(string str, out VolumeFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out VolumeFlowUnit unit) + { + return UnitParser.Default.TryParse(str, provider, out unit); + } + + #endregion + #region Arithmetic Operators public static VolumeFlow operator -(VolumeFlow right) @@ -381,6 +764,8 @@ public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] IFormatPro #endregion + #region Equality / IComparable + public static bool operator <=(VolumeFlow left, VolumeFlow right) { return left.Value <= right.AsBaseNumericType(left.Unit); @@ -401,180 +786,270 @@ public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] IFormatPro return left.Value > right.AsBaseNumericType(left.Unit); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VolumeFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator ==(VolumeFlow left, VolumeFlow right) + public static bool operator ==(VolumeFlow left, VolumeFlow right) + { + return left.Equals(right); + } + + public static bool operator !=(VolumeFlow left, VolumeFlow right) + { + return !(left == right); + } + + public int CompareTo(object obj) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + 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); } - [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(VolumeFlow, double, ComparisonType) to provide the max allowed absolute or relative error.")] - public static bool operator !=(VolumeFlow left, VolumeFlow right) + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + public int CompareTo(VolumeFlow other) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } - #region Parsing + 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)); + } /// - /// Parse a string with one or two quantities of the format "<quantity> <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. + /// /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumeFlow Parse(string str, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparisonType) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - provider = provider ?? UnitSystem.DefaultCulture; + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); - return QuantityParser.Parse(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - VolumeFlowUnit parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => FromCubicMetersPerSecond(x.CubicMetersPerSecond + y.CubicMetersPerSecond)); + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// Returns the hash code for this instance. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out VolumeFlow result) + /// A hash code for the current VolumeFlow. + public override int GetHashCode() { - provider = provider ?? UnitSystem.DefaultCulture; + return new { QuantityType, Value, Unit }.GetHashCode(); + } - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default(VolumeFlow); - return false; - } + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeFlowUnit unit) + { + if(Unit == unit) + return Convert.ToDouble(Value); + + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); } /// - /// Parse a unit string. + /// Converts this VolumeFlow to another VolumeFlow with the unit representation . /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) + /// A VolumeFlow with the specified unit. + public VolumeFlow ToUnit(VolumeFlowUnit unit) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + var convertedValue = AsBaseNumericType(unit); + return new VolumeFlow(convertedValue, unit); } /// - /// Parse a unit string. + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeFlowUnit ParseUnit(string str, IFormatProvider provider = null) + /// The value in the base unit representation. + private double AsBaseUnit() { - if (str == null) throw new ArgumentNullException(nameof(str)); + switch(Unit) + { + case VolumeFlowUnit.CentiliterPerMinute: return (_value/60000.00000) * 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; + case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; + case VolumeFlowUnit.CubicMeterPerSecond: return _value; + case VolumeFlowUnit.CubicMillimeterPerSecond: return _value*1e-9; + case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; + case VolumeFlowUnit.DeciliterPerMinute: return (_value/60000.00000) * 1e-1d; + case VolumeFlowUnit.KiloliterPerMinute: return (_value/60000.00000) * 1e3d; + case VolumeFlowUnit.KilousGallonsPerMinute: return _value/15.850323141489; + case VolumeFlowUnit.LiterPerHour: return _value/3600000.000; + case VolumeFlowUnit.LiterPerMinute: return _value/60000.00000; + case VolumeFlowUnit.LiterPerSecond: return _value/1000; + case VolumeFlowUnit.MicroliterPerMinute: return (_value/60000.00000) * 1e-6d; + case VolumeFlowUnit.MilliliterPerMinute: return (_value/60000.00000) * 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; + case VolumeFlowUnit.NanoliterPerMinute: return (_value/60000.00000) * 1e-9d; + case VolumeFlowUnit.OilBarrelPerDay: return _value*1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.OilBarrelPerHour: return _value*4.41631375e-5; + case VolumeFlowUnit.OilBarrelPerMinute: return _value*2.64978825e-3; + case VolumeFlowUnit.UsGallonPerHour: return _value/951019.38848933424; + case VolumeFlowUnit.UsGallonPerMinute: return _value/15850.323141489; + case VolumeFlowUnit.UsGallonPerSecond: return _value/264.1720523581484; + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private double AsBaseNumericType(VolumeFlowUnit unit) + { + if(Unit == unit) + return _value; - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse(str.Trim()); + var baseUnitValue = AsBaseUnit(); - if (unit == VolumeFlowUnit.Undefined) + switch(unit) { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeFlowUnit."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; + case VolumeFlowUnit.CentiliterPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; + case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; + case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; + case VolumeFlowUnit.CubicMillimeterPerSecond: return baseUnitValue/1e-9; + case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; + case VolumeFlowUnit.DeciliterPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; + case VolumeFlowUnit.KiloliterPerMinute: return (baseUnitValue*60000.00000) / 1e3d; + case VolumeFlowUnit.KilousGallonsPerMinute: return baseUnitValue*15.850323141489; + case VolumeFlowUnit.LiterPerHour: return baseUnitValue*3600000.000; + case VolumeFlowUnit.LiterPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.LiterPerSecond: return baseUnitValue*1000; + case VolumeFlowUnit.MicroliterPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; + case VolumeFlowUnit.MilliliterPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; + case VolumeFlowUnit.NanoliterPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; + case VolumeFlowUnit.OilBarrelPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.OilBarrelPerHour: return baseUnitValue/4.41631375e-5; + case VolumeFlowUnit.OilBarrelPerMinute: return baseUnitValue/2.64978825e-3; + case VolumeFlowUnit.UsGallonPerHour: return baseUnitValue*951019.38848933424; + case VolumeFlowUnit.UsGallonPerMinute: return baseUnitValue*15850.323141489; + case VolumeFlowUnit.UsGallonPerSecond: return baseUnitValue*264.1720523581484; + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } - - return unit; } #endregion #region ToString Methods + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() + { + return ToString(null); + } + /// /// Get string representation of value and unit. Using two significant digits after radix. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// String representation. - public string ToString(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return ToString(unit, provider, 2); + return ToString(provider, 2); } /// /// Get string representation of value and unit. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . /// The number of significant digits after the radix point. /// String representation. - [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } /// /// Get string representation of value and unit. /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. - [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - provider = provider ?? UnitSystem.DefaultCulture; + provider = provider ?? GlobalConfiguration.DefaultCulture; - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion + } } diff --git a/UnitsNet/GeneratedCode/QuantityType.g.cs b/UnitsNet/GeneratedCode/QuantityType.g.cs index 66145be636..470b8c5862 100644 --- a/UnitsNet/GeneratedCode/QuantityType.g.cs +++ b/UnitsNet/GeneratedCode/QuantityType.g.cs @@ -9,25 +9,24 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -82,7 +81,6 @@ public enum QuantityType ElectricResistivity, Energy, Entropy, - Flow, Force, ForceChangeRate, ForcePerLength, diff --git a/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs b/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs new file mode 100644 index 0000000000..bdaca92df2 --- /dev/null +++ b/UnitsNet/GeneratedCode/UnitAbbreviationsCache.g.cs @@ -0,0 +1,1081 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using UnitsNet.Units; + +// ReSharper disable RedundantCommaInArrayInitializer +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + public partial class UnitAbbreviationsCache + { + private static readonly (string CultureName, Type UnitType, int UnitValue, string[] UnitAbbreviations)[] GeneratedLocalizations + = new [] + { + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.CentimeterPerSecondSquared, new string[]{"cm/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.DecimeterPerSecondSquared, new string[]{"dm/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.FootPerSecondSquared, new string[]{"ft/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.InchPerSecondSquared, new string[]{"in/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.KilometerPerSecondSquared, new string[]{"km/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.KnotPerHour, new string[]{"kn/h"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.KnotPerMinute, new string[]{"kn/min"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.KnotPerSecond, new string[]{"kn/s"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.MeterPerSecondSquared, new string[]{"m/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.MicrometerPerSecondSquared, new string[]{"µm/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.MillimeterPerSecondSquared, new string[]{"mm/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.NanometerPerSecondSquared, new string[]{"nm/s²"}), + ("en-US", typeof(AccelerationUnit), (int)AccelerationUnit.StandardGravity, new string[]{"g"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Centimole, new string[]{"cmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.CentipoundMole, new string[]{"clbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Decimole, new string[]{"dmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.DecipoundMole, new string[]{"dlbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Kilomole, new string[]{"kmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.KilopoundMole, new string[]{"klbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Megamole, new string[]{"Mmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Micromole, new string[]{"µmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.MicropoundMole, new string[]{"µlbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Millimole, new string[]{"mmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.MillipoundMole, new string[]{"mlbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Mole, new string[]{"mol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.Nanomole, new string[]{"nmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.NanopoundMole, new string[]{"nlbmol"}), + ("en-US", typeof(AmountOfSubstanceUnit), (int)AmountOfSubstanceUnit.PoundMole, new string[]{"lbmol"}), + ("en-US", typeof(AmplitudeRatioUnit), (int)AmplitudeRatioUnit.DecibelMicrovolt, new string[]{"dBµV"}), + ("en-US", typeof(AmplitudeRatioUnit), (int)AmplitudeRatioUnit.DecibelMillivolt, new string[]{"dBmV"}), + ("en-US", typeof(AmplitudeRatioUnit), (int)AmplitudeRatioUnit.DecibelUnloaded, new string[]{"dBu"}), + ("en-US", typeof(AmplitudeRatioUnit), (int)AmplitudeRatioUnit.DecibelVolt, new string[]{"dBV"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Arcminute, new string[]{"'", "arcmin", "amin", "min"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Arcsecond, new string[]{"″", "arcsec", "asec", "sec"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Centiradian, new string[]{"crad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Centiradian, new string[]{"cрад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Deciradian, new string[]{"drad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Deciradian, new string[]{"dрад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Degree, new string[]{"°", "deg"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Degree, new string[]{"°"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Gradian, new string[]{"g"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Gradian, new string[]{"g"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Microdegree, new string[]{"µ°"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Microdegree, new string[]{"µ°"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Microradian, new string[]{"µrad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Microradian, new string[]{"µрад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Millidegree, new string[]{"m°"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Millidegree, new string[]{"m°"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Milliradian, new string[]{"mrad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Milliradian, new string[]{"mрад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Nanodegree, new string[]{"n°"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Nanodegree, new string[]{"n°"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Nanoradian, new string[]{"nrad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Nanoradian, new string[]{"nрад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Radian, new string[]{"rad"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Radian, new string[]{"рад"}), + ("en-US", typeof(AngleUnit), (int)AngleUnit.Revolution, new string[]{"r"}), + ("ru-RU", typeof(AngleUnit), (int)AngleUnit.Revolution, new string[]{"r"}), + ("en-US", typeof(ApparentEnergyUnit), (int)ApparentEnergyUnit.KilovoltampereHour, new string[]{"kVAh"}), + ("en-US", typeof(ApparentEnergyUnit), (int)ApparentEnergyUnit.MegavoltampereHour, new string[]{"MVAh"}), + ("en-US", typeof(ApparentEnergyUnit), (int)ApparentEnergyUnit.VoltampereHour, new string[]{"VAh"}), + ("en-US", typeof(ApparentPowerUnit), (int)ApparentPowerUnit.Gigavoltampere, new string[]{"GVA"}), + ("en-US", typeof(ApparentPowerUnit), (int)ApparentPowerUnit.Kilovoltampere, new string[]{"kVA"}), + ("en-US", typeof(ApparentPowerUnit), (int)ApparentPowerUnit.Megavoltampere, new string[]{"MVA"}), + ("en-US", typeof(ApparentPowerUnit), (int)ApparentPowerUnit.Voltampere, new string[]{"VA"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.Acre, new string[]{"ac"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.Hectare, new string[]{"ha"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareCentimeter, new string[]{"cm²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareCentimeter, new string[]{"см²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareDecimeter, new string[]{"dm²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareDecimeter, new string[]{"дм²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareFoot, new string[]{"ft²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareFoot, new string[]{"фут²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareInch, new string[]{"in²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareInch, new string[]{"дюйм²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareKilometer, new string[]{"km²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareKilometer, new string[]{"км²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareMeter, new string[]{"m²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareMeter, new string[]{"м²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareMicrometer, new string[]{"µm²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareMicrometer, new string[]{"мкм²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareMile, new string[]{"mi²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareMile, new string[]{"миля²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareMillimeter, new string[]{"mm²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareMillimeter, new string[]{"мм²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.SquareYard, new string[]{"yd²"}), + ("ru-RU", typeof(AreaUnit), (int)AreaUnit.SquareYard, new string[]{"ярд²"}), + ("en-US", typeof(AreaUnit), (int)AreaUnit.UsSurveySquareFoot, new string[]{"ft² (US)"}), + ("en-US", typeof(AreaDensityUnit), (int)AreaDensityUnit.KilogramPerSquareMeter, new string[]{"kg/m²"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.CentimeterToTheFourth, new string[]{"cm⁴", "cm^4"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.DecimeterToTheFourth, new string[]{"dm⁴", "dm^4"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.FootToTheFourth, new string[]{"ft⁴", "ft^4"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.InchToTheFourth, new string[]{"in⁴", "in^4"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.MeterToTheFourth, new string[]{"m⁴", "m^4"}), + ("en-US", typeof(AreaMomentOfInertiaUnit), (int)AreaMomentOfInertiaUnit.MillimeterToTheFourth, new string[]{"mm⁴", "mm^4"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.BitPerSecond, new string[]{"bit/s", "bps"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.BytePerSecond, new string[]{"B/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.ExabitPerSecond, new string[]{"Ebit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.ExabytePerSecond, new string[]{"EB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.ExbibitPerSecond, new string[]{"Eibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.ExbibytePerSecond, new string[]{"EiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.GibibitPerSecond, new string[]{"Gibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.GibibytePerSecond, new string[]{"GiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.GigabitPerSecond, new string[]{"Gbit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.GigabytePerSecond, new string[]{"GB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.KibibitPerSecond, new string[]{"Kibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.KibibytePerSecond, new string[]{"KiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.KilobitPerSecond, new string[]{"kbit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.KilobytePerSecond, new string[]{"kB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.MebibitPerSecond, new string[]{"Mibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.MebibytePerSecond, new string[]{"MiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.MegabitPerSecond, new string[]{"Mbit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.MegabytePerSecond, new string[]{"MB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.PebibitPerSecond, new string[]{"Pibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.PebibytePerSecond, new string[]{"PiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.PetabitPerSecond, new string[]{"Pbit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.PetabytePerSecond, new string[]{"PB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.TebibitPerSecond, new string[]{"Tibit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.TebibytePerSecond, new string[]{"TiB/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.TerabitPerSecond, new string[]{"Tbit/s"}), + ("en-US", typeof(BitRateUnit), (int)BitRateUnit.TerabytePerSecond, new string[]{"TB/s"}), + ("en-US", typeof(BrakeSpecificFuelConsumptionUnit), (int)BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, new string[]{"g/kWh"}), + ("en-US", typeof(BrakeSpecificFuelConsumptionUnit), (int)BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, new string[]{"kg/J"}), + ("en-US", typeof(BrakeSpecificFuelConsumptionUnit), (int)BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, new string[]{"lb/hph"}), + ("en-US", typeof(CapacitanceUnit), (int)CapacitanceUnit.Farad, new string[]{"F"}), + ("en-US", typeof(CapacitanceUnit), (int)CapacitanceUnit.Microfarad, new string[]{"µF"}), + ("en-US", typeof(CapacitanceUnit), (int)CapacitanceUnit.Millifarad, new string[]{"mF"}), + ("en-US", typeof(CapacitanceUnit), (int)CapacitanceUnit.Nanofarad, new string[]{"nF"}), + ("en-US", typeof(CapacitanceUnit), (int)CapacitanceUnit.Picofarad, new string[]{"pF"}), + ("en-US", typeof(CoefficientOfThermalExpansionUnit), (int)CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, new string[]{"°C⁻¹", "1/°C"}), + ("en-US", typeof(CoefficientOfThermalExpansionUnit), (int)CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, new string[]{"°F⁻¹", "1/°F"}), + ("en-US", typeof(CoefficientOfThermalExpansionUnit), (int)CoefficientOfThermalExpansionUnit.InverseKelvin, new string[]{"K⁻¹", "1/K"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.CentigramPerDeciliter, new string[]{"cg/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.CentigramPerLiter, new string[]{"cg/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.CentigramPerMilliliter, new string[]{"cg/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.DecigramPerDeciliter, new string[]{"dg/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.DecigramPerLiter, new string[]{"dg/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.DecigramPerMilliliter, new string[]{"dg/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerCubicCentimeter, new string[]{"g/cm³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerCubicMeter, new string[]{"g/m³"}), + ("ru-RU", typeof(DensityUnit), (int)DensityUnit.GramPerCubicMeter, new string[]{"г/м³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerCubicMillimeter, new string[]{"g/mm³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerDeciliter, new string[]{"g/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerLiter, new string[]{"g/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.GramPerMilliliter, new string[]{"g/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.KilogramPerCubicCentimeter, new string[]{"kg/cm³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.KilogramPerCubicMeter, new string[]{"kg/m³"}), + ("ru-RU", typeof(DensityUnit), (int)DensityUnit.KilogramPerCubicMeter, new string[]{"kг/м³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.KilogramPerCubicMillimeter, new string[]{"kg/mm³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.KilopoundPerCubicFoot, new string[]{"kip/ft³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.KilopoundPerCubicInch, new string[]{"kip/in³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MicrogramPerDeciliter, new string[]{"µg/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MicrogramPerLiter, new string[]{"µg/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MicrogramPerMilliliter, new string[]{"µg/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MilligramPerCubicMeter, new string[]{"mg/m³"}), + ("ru-RU", typeof(DensityUnit), (int)DensityUnit.MilligramPerCubicMeter, new string[]{"mг/м³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MilligramPerDeciliter, new string[]{"mg/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MilligramPerLiter, new string[]{"mg/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.MilligramPerMilliliter, new string[]{"mg/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.NanogramPerDeciliter, new string[]{"ng/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.NanogramPerLiter, new string[]{"ng/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.NanogramPerMilliliter, new string[]{"ng/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PicogramPerDeciliter, new string[]{"pg/dl"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PicogramPerLiter, new string[]{"pg/L"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PicogramPerMilliliter, new string[]{"pg/ml"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PoundPerCubicFoot, new string[]{"lb/ft³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PoundPerCubicInch, new string[]{"lb/in³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PoundPerImperialGallon, new string[]{"ppg (imp.)"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.PoundPerUSGallon, new string[]{"ppg (U.S.)"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.SlugPerCubicFoot, new string[]{"slug/ft³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.TonnePerCubicCentimeter, new string[]{"t/cm³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.TonnePerCubicMeter, new string[]{"t/m³"}), + ("en-US", typeof(DensityUnit), (int)DensityUnit.TonnePerCubicMillimeter, new string[]{"t/mm³"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Day, new string[]{"d", "day", "days"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Day, new string[]{"д"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Hour, new string[]{"h", "hr", "hrs", "hour", "hours"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Hour, new string[]{"ч"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Microsecond, new string[]{"µs"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Microsecond, new string[]{"мкс"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Millisecond, new string[]{"ms"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Millisecond, new string[]{"мс"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Minute, new string[]{"m", "min", "minute", "minutes"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Minute, new string[]{"мин"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Month30, new string[]{"mo", "month", "months"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Month30, new string[]{"месяц"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Nanosecond, new string[]{"ns"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Nanosecond, new string[]{"нс"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Second, new string[]{"s", "sec", "secs", "second", "seconds"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Second, new string[]{"с"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Week, new string[]{"wk", "week", "weeks"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Week, new string[]{"мин"}), + ("en-US", typeof(DurationUnit), (int)DurationUnit.Year365, new string[]{"yr", "year", "years"}), + ("ru-RU", typeof(DurationUnit), (int)DurationUnit.Year365, new string[]{"год"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.Centipoise, new string[]{"cP"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.MicropascalSecond, new string[]{"µPaS"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.MillipascalSecond, new string[]{"mPaS"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.NewtonSecondPerMeterSquared, new string[]{"Ns/m²"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.PascalSecond, new string[]{"PaS"}), + ("en-US", typeof(DynamicViscosityUnit), (int)DynamicViscosityUnit.Poise, new string[]{"P"}), + ("en-US", typeof(ElectricAdmittanceUnit), (int)ElectricAdmittanceUnit.Microsiemens, new string[]{"µS"}), + ("en-US", typeof(ElectricAdmittanceUnit), (int)ElectricAdmittanceUnit.Millisiemens, new string[]{"mS"}), + ("en-US", typeof(ElectricAdmittanceUnit), (int)ElectricAdmittanceUnit.Nanosiemens, new string[]{"nS"}), + ("en-US", typeof(ElectricAdmittanceUnit), (int)ElectricAdmittanceUnit.Siemens, new string[]{"S"}), + ("en-US", typeof(ElectricChargeUnit), (int)ElectricChargeUnit.Coulomb, new string[]{"C"}), + ("en-US", typeof(ElectricChargeDensityUnit), (int)ElectricChargeDensityUnit.CoulombPerCubicMeter, new string[]{"C/m³"}), + ("en-US", typeof(ElectricConductanceUnit), (int)ElectricConductanceUnit.Microsiemens, new string[]{"µS"}), + ("en-US", typeof(ElectricConductanceUnit), (int)ElectricConductanceUnit.Millisiemens, new string[]{"mS"}), + ("en-US", typeof(ElectricConductanceUnit), (int)ElectricConductanceUnit.Siemens, new string[]{"S"}), + ("en-US", typeof(ElectricConductivityUnit), (int)ElectricConductivityUnit.SiemensPerMeter, new string[]{"S/m"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Ampere, new string[]{"A"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Centiampere, new string[]{"cA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Kiloampere, new string[]{"kA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Megaampere, new string[]{"MA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Microampere, new string[]{"µA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Milliampere, new string[]{"mA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Nanoampere, new string[]{"nA"}), + ("en-US", typeof(ElectricCurrentUnit), (int)ElectricCurrentUnit.Picoampere, new string[]{"pA"}), + ("en-US", typeof(ElectricCurrentDensityUnit), (int)ElectricCurrentDensityUnit.AmperePerSquareMeter, new string[]{"A/m²"}), + ("en-US", typeof(ElectricCurrentGradientUnit), (int)ElectricCurrentGradientUnit.AmperePerSecond, new string[]{"A/s"}), + ("en-US", typeof(ElectricFieldUnit), (int)ElectricFieldUnit.VoltPerMeter, new string[]{"V/m"}), + ("en-US", typeof(ElectricInductanceUnit), (int)ElectricInductanceUnit.Henry, new string[]{"H"}), + ("en-US", typeof(ElectricInductanceUnit), (int)ElectricInductanceUnit.Microhenry, new string[]{"µH"}), + ("en-US", typeof(ElectricInductanceUnit), (int)ElectricInductanceUnit.Millihenry, new string[]{"mH"}), + ("en-US", typeof(ElectricInductanceUnit), (int)ElectricInductanceUnit.Nanohenry, new string[]{"nH"}), + ("en-US", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Kilovolt, new string[]{"kV"}), + ("ru-RU", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Kilovolt, new string[]{"kВ"}), + ("en-US", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Megavolt, new string[]{"MV"}), + ("ru-RU", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Megavolt, new string[]{"MВ"}), + ("en-US", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Microvolt, new string[]{"µV"}), + ("ru-RU", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Microvolt, new string[]{"µВ"}), + ("en-US", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Millivolt, new string[]{"mV"}), + ("ru-RU", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Millivolt, new string[]{"mВ"}), + ("en-US", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Volt, new string[]{"V"}), + ("ru-RU", typeof(ElectricPotentialUnit), (int)ElectricPotentialUnit.Volt, new string[]{"В"}), + ("en-US", typeof(ElectricPotentialAcUnit), (int)ElectricPotentialAcUnit.KilovoltAc, new string[]{"kVac"}), + ("en-US", typeof(ElectricPotentialAcUnit), (int)ElectricPotentialAcUnit.MegavoltAc, new string[]{"MVac"}), + ("en-US", typeof(ElectricPotentialAcUnit), (int)ElectricPotentialAcUnit.MicrovoltAc, new string[]{"µVac"}), + ("en-US", typeof(ElectricPotentialAcUnit), (int)ElectricPotentialAcUnit.MillivoltAc, new string[]{"mVac"}), + ("en-US", typeof(ElectricPotentialAcUnit), (int)ElectricPotentialAcUnit.VoltAc, new string[]{"Vac"}), + ("en-US", typeof(ElectricPotentialDcUnit), (int)ElectricPotentialDcUnit.KilovoltDc, new string[]{"kVdc"}), + ("en-US", typeof(ElectricPotentialDcUnit), (int)ElectricPotentialDcUnit.MegavoltDc, new string[]{"MVdc"}), + ("en-US", typeof(ElectricPotentialDcUnit), (int)ElectricPotentialDcUnit.MicrovoltDc, new string[]{"µVdc"}), + ("en-US", typeof(ElectricPotentialDcUnit), (int)ElectricPotentialDcUnit.MillivoltDc, new string[]{"mVdc"}), + ("en-US", typeof(ElectricPotentialDcUnit), (int)ElectricPotentialDcUnit.VoltDc, new string[]{"Vdc"}), + ("en-US", typeof(ElectricResistanceUnit), (int)ElectricResistanceUnit.Gigaohm, new string[]{"GΩ"}), + ("en-US", typeof(ElectricResistanceUnit), (int)ElectricResistanceUnit.Kiloohm, new string[]{"kΩ"}), + ("en-US", typeof(ElectricResistanceUnit), (int)ElectricResistanceUnit.Megaohm, new string[]{"MΩ"}), + ("en-US", typeof(ElectricResistanceUnit), (int)ElectricResistanceUnit.Milliohm, new string[]{"mΩ"}), + ("en-US", typeof(ElectricResistanceUnit), (int)ElectricResistanceUnit.Ohm, new string[]{"Ω"}), + ("en-US", typeof(ElectricResistivityUnit), (int)ElectricResistivityUnit.MicroohmMeter, new string[]{"µΩ·m"}), + ("en-US", typeof(ElectricResistivityUnit), (int)ElectricResistivityUnit.MilliohmMeter, new string[]{"mΩ·m"}), + ("en-US", typeof(ElectricResistivityUnit), (int)ElectricResistivityUnit.NanoohmMeter, new string[]{"nΩ·m"}), + ("en-US", typeof(ElectricResistivityUnit), (int)ElectricResistivityUnit.OhmMeter, new string[]{"Ω·m"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.BritishThermalUnit, new string[]{"BTU"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Calorie, new string[]{"cal"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.DecathermEc, new string[]{"Dth (E.C.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.DecathermEc, new string[]{"Европейский декатерм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.DecathermImperial, new string[]{"Dth (imp.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.DecathermImperial, new string[]{"Английский декатерм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.DecathermUs, new string[]{"Dth (U.S.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.DecathermUs, new string[]{"Американский декатерм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.ElectronVolt, new string[]{"eV"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Erg, new string[]{"erg"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.FootPound, new string[]{"ft·lb"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.GigabritishThermalUnit, new string[]{"GBTU"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.GigawattHour, new string[]{"GWh"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.GigawattHour, new string[]{"GВт/ч"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Joule, new string[]{"J"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.KilobritishThermalUnit, new string[]{"kBTU"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Kilocalorie, new string[]{"kcal"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Kilojoule, new string[]{"kJ"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.KilowattHour, new string[]{"kWh"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.KilowattHour, new string[]{"kВт/ч"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.MegabritishThermalUnit, new string[]{"MBTU"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.Megajoule, new string[]{"MJ"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.MegawattHour, new string[]{"MWh"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.MegawattHour, new string[]{"MВт/ч"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.ThermEc, new string[]{"th (E.C.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.ThermEc, new string[]{"Европейский терм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.ThermImperial, new string[]{"th (imp.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.ThermImperial, new string[]{"Английский терм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.ThermUs, new string[]{"th (U.S.)"}), + ("ru-RU", typeof(EnergyUnit), (int)EnergyUnit.ThermUs, new string[]{"Американский терм"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.WattHour, new string[]{"Wh"}), + ("en-US", typeof(EnergyUnit), (int)EnergyUnit.WattHour, new string[]{"Вт/ч"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.CaloriePerKelvin, new string[]{"cal/K"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.JoulePerDegreeCelsius, new string[]{"J/C"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.JoulePerKelvin, new string[]{"J/K"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.KilocaloriePerKelvin, new string[]{"kcal/K"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.KilojoulePerDegreeCelsius, new string[]{"kJ/C"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.KilojoulePerKelvin, new string[]{"kJ/K"}), + ("en-US", typeof(EntropyUnit), (int)EntropyUnit.MegajoulePerKelvin, new string[]{"MJ/K"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Decanewton, new string[]{"daN"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Decanewton, new string[]{"даН"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Dyn, new string[]{"dyn"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Dyn, new string[]{"дин"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.KilogramForce, new string[]{"kgf"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.KilogramForce, new string[]{"кгс"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Kilonewton, new string[]{"kN"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Kilonewton, new string[]{"кН"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.KiloPond, new string[]{"kp"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.KiloPond, new string[]{"кгс"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Meganewton, new string[]{"MN"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Meganewton, new string[]{"МН"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Micronewton, new string[]{"µN"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Micronewton, new string[]{"мкН"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Millinewton, new string[]{"mN"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Millinewton, new string[]{"мН"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Newton, new string[]{"N"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Newton, new string[]{"Н"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.OunceForce, new string[]{"ozf"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.Poundal, new string[]{"pdl"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.Poundal, new string[]{"паундаль"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.PoundForce, new string[]{"lbf"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.PoundForce, new string[]{"фунт-сила"}), + ("en-US", typeof(ForceUnit), (int)ForceUnit.TonneForce, new string[]{"Ton"}), + ("ru-RU", typeof(ForceUnit), (int)ForceUnit.TonneForce, new string[]{"тс"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.CentinewtonPerSecond, new string[]{"cN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.DecanewtonPerMinute, new string[]{"daN/min"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.DecanewtonPerSecond, new string[]{"daN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.DecinewtonPerSecond, new string[]{"dN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.KilonewtonPerMinute, new string[]{"kN/min"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.KilonewtonPerSecond, new string[]{"kN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.MicronewtonPerSecond, new string[]{"µN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.MillinewtonPerSecond, new string[]{"mN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.NanonewtonPerSecond, new string[]{"nN/s"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.NewtonPerMinute, new string[]{"N/min"}), + ("en-US", typeof(ForceChangeRateUnit), (int)ForceChangeRateUnit.NewtonPerSecond, new string[]{"N/s"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.CentinewtonPerMeter, new string[]{"cN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.DecinewtonPerMeter, new string[]{"dN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.KilogramForcePerMeter, new string[]{"kgf/m"}), + ("ru-RU", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.KilogramForcePerMeter, new string[]{"кгс/м"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.KilonewtonPerMeter, new string[]{"kN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.MeganewtonPerMeter, new string[]{"MN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.MicronewtonPerMeter, new string[]{"µN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.MillinewtonPerMeter, new string[]{"mN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.NanonewtonPerMeter, new string[]{"nN/m"}), + ("en-US", typeof(ForcePerLengthUnit), (int)ForcePerLengthUnit.NewtonPerMeter, new string[]{"N/m"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.CyclePerHour, new string[]{"cph"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.CyclePerMinute, new string[]{"cpm"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.Gigahertz, new string[]{"GHz"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.Hertz, new string[]{"Hz"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.Kilohertz, new string[]{"kHz"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.Megahertz, new string[]{"MHz"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.RadianPerSecond, new string[]{"rad/s"}), + ("en-US", typeof(FrequencyUnit), (int)FrequencyUnit.Terahertz, new string[]{"THz"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.BtuPerHourSquareFoot, new string[]{"BTU/h·ft²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.BtuPerMinuteSquareFoot, new string[]{"BTU/min·ft²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.BtuPerSecondSquareFoot, new string[]{"BTU/s·ft²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.BtuPerSecondSquareInch, new string[]{"BTU/s·in²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.CaloriePerSecondSquareCentimeter, new string[]{"cal/s·cm²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.CentiwattPerSquareMeter, new string[]{"cW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.DeciwattPerSquareMeter, new string[]{"dW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.KilocaloriePerHourSquareMeter, new string[]{"kcal/h·m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, new string[]{"kcal/s·cm²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.KilowattPerSquareMeter, new string[]{"kW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.MicrowattPerSquareMeter, new string[]{"µW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.MilliwattPerSquareMeter, new string[]{"mW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.NanowattPerSquareMeter, new string[]{"nW/m²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.PoundForcePerFootSecond, new string[]{"lbf/(ft·s)"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.PoundPerSecondCubed, new string[]{"lb/s³", "lbm/s³"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.WattPerSquareFoot, new string[]{"W/ft²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.WattPerSquareInch, new string[]{"W/in²"}), + ("en-US", typeof(HeatFluxUnit), (int)HeatFluxUnit.WattPerSquareMeter, new string[]{"W/m²"}), + ("en-US", typeof(HeatTransferCoefficientUnit), (int)HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, new string[]{"W/m²·°C"}), + ("en-US", typeof(HeatTransferCoefficientUnit), (int)HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, new string[]{"W/m²·K"}), + ("en-US", typeof(IlluminanceUnit), (int)IlluminanceUnit.Kilolux, new string[]{"klx"}), + ("en-US", typeof(IlluminanceUnit), (int)IlluminanceUnit.Lux, new string[]{"lx"}), + ("en-US", typeof(IlluminanceUnit), (int)IlluminanceUnit.Megalux, new string[]{"Mlx"}), + ("en-US", typeof(IlluminanceUnit), (int)IlluminanceUnit.Millilux, new string[]{"mlx"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Bit, new string[]{"b"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Byte, new string[]{"B"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Exabit, new string[]{"Eb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Exabyte, new string[]{"EB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Exbibit, new string[]{"Eib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Exbibyte, new string[]{"EiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Gibibit, new string[]{"Gib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Gibibyte, new string[]{"GiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Gigabit, new string[]{"Gb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Gigabyte, new string[]{"GB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Kibibit, new string[]{"Kib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Kibibyte, new string[]{"KiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Kilobit, new string[]{"kb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Kilobyte, new string[]{"kB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Mebibit, new string[]{"Mib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Mebibyte, new string[]{"MiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Megabit, new string[]{"Mb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Megabyte, new string[]{"MB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Pebibit, new string[]{"Pib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Pebibyte, new string[]{"PiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Petabit, new string[]{"Pb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Petabyte, new string[]{"PB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Tebibit, new string[]{"Tib"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Tebibyte, new string[]{"TiB"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Terabit, new string[]{"Tb"}), + ("en-US", typeof(InformationUnit), (int)InformationUnit.Terabyte, new string[]{"TB"}), + ("en-US", typeof(IrradianceUnit), (int)IrradianceUnit.KilowattPerSquareMeter, new string[]{"kW/m²"}), + ("en-US", typeof(IrradianceUnit), (int)IrradianceUnit.WattPerSquareMeter, new string[]{"W/m²"}), + ("en-US", typeof(IrradiationUnit), (int)IrradiationUnit.JoulePerSquareMeter, new string[]{"J/m²"}), + ("en-US", typeof(IrradiationUnit), (int)IrradiationUnit.KilowattHourPerSquareMeter, new string[]{"kWh/m²"}), + ("en-US", typeof(IrradiationUnit), (int)IrradiationUnit.WattHourPerSquareMeter, new string[]{"Wh/m²"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Centistokes, new string[]{"cSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Centistokes, new string[]{"сСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Decistokes, new string[]{"dSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Decistokes, new string[]{"дСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Kilostokes, new string[]{"kSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Kilostokes, new string[]{"кСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Microstokes, new string[]{"µSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Microstokes, new string[]{"мкСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Millistokes, new string[]{"mSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Millistokes, new string[]{"мСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Nanostokes, new string[]{"nSt"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Nanostokes, new string[]{"нСт"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.SquareMeterPerSecond, new string[]{"m²/s"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.SquareMeterPerSecond, new string[]{"м²/с"}), + ("en-US", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Stokes, new string[]{"St"}), + ("ru-RU", typeof(KinematicViscosityUnit), (int)KinematicViscosityUnit.Stokes, new string[]{"Ст"}), + ("en-US", typeof(LapseRateUnit), (int)LapseRateUnit.DegreeCelsiusPerKilometer, new string[]{"∆°C/km"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Centimeter, new string[]{"cm"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Centimeter, new string[]{"см"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Decimeter, new string[]{"dm"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Decimeter, new string[]{"дм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.DtpPica, new string[]{"pica"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.DtpPoint, new string[]{"pt"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Fathom, new string[]{"fathom"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Foot, new string[]{"ft", "'", "′"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Foot, new string[]{"фут"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Inch, new string[]{"in", "\"", "″"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Inch, new string[]{"дюйм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Kilometer, new string[]{"km"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Kilometer, new string[]{"км"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Meter, new string[]{"m"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Meter, new string[]{"м"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Microinch, new string[]{"µin"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Microinch, new string[]{"микродюйм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Micrometer, new string[]{"µm"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Micrometer, new string[]{"мкм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Mil, new string[]{"mil"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Mil, new string[]{"мил"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Mile, new string[]{"mi"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Mile, new string[]{"миля"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Millimeter, new string[]{"mm"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Millimeter, new string[]{"мм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Nanometer, new string[]{"nm"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Nanometer, new string[]{"нм"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.NauticalMile, new string[]{"NM"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.NauticalMile, new string[]{"мил"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.PrinterPica, new string[]{"pica"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.PrinterPoint, new string[]{"pt"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Shackle, new string[]{"shackle"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Twip, new string[]{"twip"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.UsSurveyFoot, new string[]{"ftUS"}), + ("en-US", typeof(LengthUnit), (int)LengthUnit.Yard, new string[]{"yd"}), + ("ru-RU", typeof(LengthUnit), (int)LengthUnit.Yard, new string[]{"ярд"}), + ("en-US", typeof(LevelUnit), (int)LevelUnit.Decibel, new string[]{"dB"}), + ("en-US", typeof(LevelUnit), (int)LevelUnit.Neper, new string[]{"Np"}), + ("en-US", typeof(LinearDensityUnit), (int)LinearDensityUnit.GramPerMeter, new string[]{"g/m"}), + ("en-US", typeof(LinearDensityUnit), (int)LinearDensityUnit.KilogramPerMeter, new string[]{"kg/m"}), + ("en-US", typeof(LinearDensityUnit), (int)LinearDensityUnit.PoundPerFoot, new string[]{"lb/ft"}), + ("en-US", typeof(LuminousFluxUnit), (int)LuminousFluxUnit.Lumen, new string[]{"lm"}), + ("en-US", typeof(LuminousIntensityUnit), (int)LuminousIntensityUnit.Candela, new string[]{"cd"}), + ("en-US", typeof(MagneticFieldUnit), (int)MagneticFieldUnit.Microtesla, new string[]{"µT"}), + ("en-US", typeof(MagneticFieldUnit), (int)MagneticFieldUnit.Millitesla, new string[]{"mT"}), + ("en-US", typeof(MagneticFieldUnit), (int)MagneticFieldUnit.Nanotesla, new string[]{"nT"}), + ("en-US", typeof(MagneticFieldUnit), (int)MagneticFieldUnit.Tesla, new string[]{"T"}), + ("en-US", typeof(MagneticFluxUnit), (int)MagneticFluxUnit.Weber, new string[]{"Wb"}), + ("en-US", typeof(MagnetizationUnit), (int)MagnetizationUnit.AmperePerMeter, new string[]{"A/m"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Centigram, new string[]{"cg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Centigram, new string[]{"сг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Decagram, new string[]{"dag"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Decagram, new string[]{"даг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Decigram, new string[]{"dg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Decigram, new string[]{"дг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Gram, new string[]{"g"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Gram, new string[]{"г"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Hectogram, new string[]{"hg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Hectogram, new string[]{"гг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Kilogram, new string[]{"kg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Kilogram, new string[]{"кг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Kilopound, new string[]{"klb"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Kilopound, new string[]{"kфунт"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Kilotonne, new string[]{"kt"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Kilotonne, new string[]{"кт"}), + ("en-US", typeof(MassUnit), (int)MassUnit.LongHundredweight, new string[]{"cwt"}), + ("en-US", typeof(MassUnit), (int)MassUnit.LongTon, new string[]{"long tn"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.LongTon, new string[]{"тонна большая"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Megapound, new string[]{"Mlb"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Megapound, new string[]{"Mфунт"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Megatonne, new string[]{"Mt"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Megatonne, new string[]{"Мт"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Microgram, new string[]{"µg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Microgram, new string[]{"мкг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Milligram, new string[]{"mg"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Milligram, new string[]{"мг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Nanogram, new string[]{"ng"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Nanogram, new string[]{"нг"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Ounce, new string[]{"oz"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Pound, new string[]{"lb", "lbs", "lbm"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Pound, new string[]{"фунт"}), + ("en-US", typeof(MassUnit), (int)MassUnit.ShortHundredweight, new string[]{"cwt"}), + ("en-US", typeof(MassUnit), (int)MassUnit.ShortTon, new string[]{"short tn"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.ShortTon, new string[]{"тонна малая"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Slug, new string[]{"slug"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Stone, new string[]{"st"}), + ("en-US", typeof(MassUnit), (int)MassUnit.Tonne, new string[]{"t"}), + ("ru-RU", typeof(MassUnit), (int)MassUnit.Tonne, new string[]{"т"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.CentigramPerSecond, new string[]{"cg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.DecagramPerSecond, new string[]{"dag/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.DecigramPerSecond, new string[]{"dg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.GramPerSecond, new string[]{"g/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.HectogramPerSecond, new string[]{"hg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.KilogramPerHour, new string[]{"kg/h"}), + ("ru-RU", typeof(MassFlowUnit), (int)MassFlowUnit.KilogramPerHour, new string[]{"кг/ч"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.KilogramPerMinute, new string[]{"kg/min"}), + ("ru-RU", typeof(MassFlowUnit), (int)MassFlowUnit.KilogramPerMinute, new string[]{"кг/мин"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.KilogramPerSecond, new string[]{"kg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.MegapoundPerHour, new string[]{"Mlb/h"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.MegapoundPerMinute, new string[]{"Mlb/min"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.MicrogramPerSecond, new string[]{"µg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.MilligramPerSecond, new string[]{"mg/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.NanogramPerSecond, new string[]{"ng/S"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.PoundPerHour, new string[]{"lb/h"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.PoundPerMinute, new string[]{"lb/min"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.ShortTonPerHour, new string[]{"short tn/h"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.TonnePerDay, new string[]{"t/d"}), + ("en-US", typeof(MassFlowUnit), (int)MassFlowUnit.TonnePerHour, new string[]{"t/h"}), + ("en-US", typeof(MassFluxUnit), (int)MassFluxUnit.GramPerSecondPerSquareMeter, new string[]{"g·s⁻¹·m⁻²"}), + ("en-US", typeof(MassFluxUnit), (int)MassFluxUnit.KilogramPerSecondPerSquareMeter, new string[]{"kg·s⁻¹·m⁻²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.GramSquareCentimeter, new string[]{"g·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.GramSquareDecimeter, new string[]{"g·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.GramSquareMeter, new string[]{"g·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.GramSquareMillimeter, new string[]{"g·mm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilogramSquareCentimeter, new string[]{"kg·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilogramSquareDecimeter, new string[]{"kg·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilogramSquareMeter, new string[]{"kg·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilogramSquareMillimeter, new string[]{"kg·mm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilotonneSquareCentimeter, new string[]{"kt·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilotonneSquareDecimeter, new string[]{"kt·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilotonneSquareMeter, new string[]{"kt·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.KilotonneSquareMilimeter, new string[]{"kt·mm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MegatonneSquareCentimeter, new string[]{"Mt·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MegatonneSquareDecimeter, new string[]{"Mt·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MegatonneSquareMeter, new string[]{"Mt·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MegatonneSquareMilimeter, new string[]{"Mt·mm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MilligramSquareCentimeter, new string[]{"mg·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MilligramSquareDecimeter, new string[]{"mg·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MilligramSquareMeter, new string[]{"mg·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.MilligramSquareMillimeter, new string[]{"mg·mm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.PoundSquareFoot, new string[]{"lb·ft²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.PoundSquareInch, new string[]{"lb·in²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.SlugSquareFoot, new string[]{"slug·ft²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.SlugSquareInch, new string[]{"slug·in²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.TonneSquareCentimeter, new string[]{"t·cm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.TonneSquareDecimeter, new string[]{"t·dm²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.TonneSquareMeter, new string[]{"t·m²"}), + ("en-US", typeof(MassMomentOfInertiaUnit), (int)MassMomentOfInertiaUnit.TonneSquareMilimeter, new string[]{"t·mm²"}), + ("en-US", typeof(MolarEnergyUnit), (int)MolarEnergyUnit.JoulePerMole, new string[]{"J/mol"}), + ("en-US", typeof(MolarEnergyUnit), (int)MolarEnergyUnit.KilojoulePerMole, new string[]{"kJ/mol"}), + ("en-US", typeof(MolarEnergyUnit), (int)MolarEnergyUnit.MegajoulePerMole, new string[]{"MJ/mol"}), + ("en-US", typeof(MolarEntropyUnit), (int)MolarEntropyUnit.JoulePerMoleKelvin, new string[]{"J/(mol*K)"}), + ("en-US", typeof(MolarEntropyUnit), (int)MolarEntropyUnit.KilojoulePerMoleKelvin, new string[]{"kJ/(mol*K)"}), + ("en-US", typeof(MolarEntropyUnit), (int)MolarEntropyUnit.MegajoulePerMoleKelvin, new string[]{"MJ/(mol*K)"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.CentimolesPerLiter, new string[]{"cmol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.DecimolesPerLiter, new string[]{"dmol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.MicromolesPerLiter, new string[]{"µmol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.MillimolesPerLiter, new string[]{"mmol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.MolesPerCubicMeter, new string[]{"mol/m³"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.MolesPerLiter, new string[]{"mol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.NanomolesPerLiter, new string[]{"nmol/L"}), + ("en-US", typeof(MolarityUnit), (int)MolarityUnit.PicomolesPerLiter, new string[]{"pmol/L"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.CentigramPerMole, new string[]{"cg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.CentigramPerMole, new string[]{"сг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.DecagramPerMole, new string[]{"dag/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.DecagramPerMole, new string[]{"даг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.DecigramPerMole, new string[]{"dg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.DecigramPerMole, new string[]{"дг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.GramPerMole, new string[]{"g/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.GramPerMole, new string[]{"г/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.HectogramPerMole, new string[]{"hg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.HectogramPerMole, new string[]{"гг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.KilogramPerMole, new string[]{"kg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.KilogramPerMole, new string[]{"кг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.KilopoundPerMole, new string[]{"klb/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.KilopoundPerMole, new string[]{"kфунт/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.MegapoundPerMole, new string[]{"Mlb/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.MegapoundPerMole, new string[]{"Mфунт/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.MicrogramPerMole, new string[]{"µg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.MicrogramPerMole, new string[]{"мкг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.MilligramPerMole, new string[]{"mg/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.MilligramPerMole, new string[]{"мг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.NanogramPerMole, new string[]{"ng/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.NanogramPerMole, new string[]{"нг/моль"}), + ("en-US", typeof(MolarMassUnit), (int)MolarMassUnit.PoundPerMole, new string[]{"lb/mol"}), + ("ru-RU", typeof(MolarMassUnit), (int)MolarMassUnit.PoundPerMole, new string[]{"фунт/моль"}), + ("en-US", typeof(PermeabilityUnit), (int)PermeabilityUnit.HenryPerMeter, new string[]{"H/m"}), + ("en-US", typeof(PermittivityUnit), (int)PermittivityUnit.FaradPerMeter, new string[]{"F/m"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.BoilerHorsepower, new string[]{"hp(S)"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.BritishThermalUnitPerHour, new string[]{"Btu/hr"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Decawatt, new string[]{"daW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Deciwatt, new string[]{"dW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.ElectricalHorsepower, new string[]{"hp(E)"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Femtowatt, new string[]{"fW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Gigawatt, new string[]{"GW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.HydraulicHorsepower, new string[]{"hp(H)"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.KilobritishThermalUnitPerHour, new string[]{"kBtu/hr"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Kilowatt, new string[]{"kW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.MechanicalHorsepower, new string[]{"hp(I)"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Megawatt, new string[]{"MW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.MetricHorsepower, new string[]{"hp(M)"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Microwatt, new string[]{"µW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Milliwatt, new string[]{"mW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Nanowatt, new string[]{"nW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Petawatt, new string[]{"PW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Picowatt, new string[]{"pW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Terawatt, new string[]{"TW"}), + ("en-US", typeof(PowerUnit), (int)PowerUnit.Watt, new string[]{"W"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DecawattPerCubicFoot, new string[]{"daW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DecawattPerCubicInch, new string[]{"daW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DecawattPerCubicMeter, new string[]{"daW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DecawattPerLiter, new string[]{"daW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DeciwattPerCubicFoot, new string[]{"dW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DeciwattPerCubicInch, new string[]{"dW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DeciwattPerCubicMeter, new string[]{"dW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.DeciwattPerLiter, new string[]{"dW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.GigawattPerCubicFoot, new string[]{"GW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.GigawattPerCubicInch, new string[]{"GW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.GigawattPerCubicMeter, new string[]{"GW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.GigawattPerLiter, new string[]{"GW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.KilowattPerCubicFoot, new string[]{"kW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.KilowattPerCubicInch, new string[]{"kW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.KilowattPerCubicMeter, new string[]{"kW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.KilowattPerLiter, new string[]{"kW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MegawattPerCubicFoot, new string[]{"MW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MegawattPerCubicInch, new string[]{"MW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MegawattPerCubicMeter, new string[]{"MW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MegawattPerLiter, new string[]{"MW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MicrowattPerCubicFoot, new string[]{"µW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MicrowattPerCubicInch, new string[]{"µW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MicrowattPerCubicMeter, new string[]{"µW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MicrowattPerLiter, new string[]{"µW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MilliwattPerCubicFoot, new string[]{"mW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MilliwattPerCubicInch, new string[]{"mW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MilliwattPerCubicMeter, new string[]{"mW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.MilliwattPerLiter, new string[]{"mW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.NanowattPerCubicFoot, new string[]{"nW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.NanowattPerCubicInch, new string[]{"nW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.NanowattPerCubicMeter, new string[]{"nW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.NanowattPerLiter, new string[]{"nW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.PicowattPerCubicFoot, new string[]{"pW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.PicowattPerCubicInch, new string[]{"pW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.PicowattPerCubicMeter, new string[]{"pW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.PicowattPerLiter, new string[]{"pW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.TerawattPerCubicFoot, new string[]{"TW/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.TerawattPerCubicInch, new string[]{"TW/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.TerawattPerCubicMeter, new string[]{"TW/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.TerawattPerLiter, new string[]{"TW/l"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.WattPerCubicFoot, new string[]{"W/ft³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.WattPerCubicInch, new string[]{"W/in³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.WattPerCubicMeter, new string[]{"W/m³"}), + ("en-US", typeof(PowerDensityUnit), (int)PowerDensityUnit.WattPerLiter, new string[]{"W/l"}), + ("en-US", typeof(PowerRatioUnit), (int)PowerRatioUnit.DecibelMilliwatt, new string[]{"dBmW", "dBm"}), + ("en-US", typeof(PowerRatioUnit), (int)PowerRatioUnit.DecibelWatt, new string[]{"dBW"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Atmosphere, new string[]{"atm"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Atmosphere, new string[]{"атм"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Bar, new string[]{"bar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Bar, new string[]{"бар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Centibar, new string[]{"cbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Centibar, new string[]{"cбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Decapascal, new string[]{"daPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Decapascal, new string[]{"даПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Decibar, new string[]{"dbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Decibar, new string[]{"dбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.DynePerSquareCentimeter, new string[]{"dyn/cm²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.FootOfHead, new string[]{"ft of head"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Gigapascal, new string[]{"GPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Gigapascal, new string[]{"ГПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Hectopascal, new string[]{"hPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Hectopascal, new string[]{"гПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.InchOfMercury, new string[]{"inHg"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Kilobar, new string[]{"kbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Kilobar, new string[]{"kбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareCentimeter, new string[]{"kgf/cm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareCentimeter, new string[]{"кгс/см²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareMeter, new string[]{"kgf/m²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareMeter, new string[]{"кгс/м²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareMillimeter, new string[]{"kgf/mm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilogramForcePerSquareMillimeter, new string[]{"кгс/мм²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareCentimeter, new string[]{"kN/cm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareCentimeter, new string[]{"кН/см²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareMeter, new string[]{"kN/m²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareMeter, new string[]{"кН/м²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareMillimeter, new string[]{"kN/mm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.KilonewtonPerSquareMillimeter, new string[]{"кН/мм²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Kilopascal, new string[]{"kPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Kilopascal, new string[]{"кПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilopoundForcePerSquareFoot, new string[]{"kipf/ft²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.KilopoundForcePerSquareInch, new string[]{"kipf/in²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Megabar, new string[]{"Mbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Megabar, new string[]{"Mбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.MeganewtonPerSquareMeter, new string[]{"MN/m²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.MeganewtonPerSquareMeter, new string[]{"Мн/м²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Megapascal, new string[]{"MPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Megapascal, new string[]{"МПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.MeterOfHead, new string[]{"m of head"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Microbar, new string[]{"µbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Microbar, new string[]{"µбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Micropascal, new string[]{"µPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Micropascal, new string[]{"мкПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Millibar, new string[]{"mbar"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Millibar, new string[]{"mбар"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.MillimeterOfMercury, new string[]{"mmHg"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Millipascal, new string[]{"mPa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Millipascal, new string[]{"ммПа"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareCentimeter, new string[]{"N/cm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareCentimeter, new string[]{"Н/см²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareMeter, new string[]{"N/m²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareMeter, new string[]{"Н/м²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareMillimeter, new string[]{"N/mm²"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.NewtonPerSquareMillimeter, new string[]{"Н/мм²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Pascal, new string[]{"Pa"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Pascal, new string[]{"Па"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.PoundForcePerSquareFoot, new string[]{"lb/ft²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.PoundForcePerSquareInch, new string[]{"psi", "lb/in²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.PoundPerInchSecondSquared, new string[]{"lbm/(in·s²)", "lb/(in·s²)"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.TechnicalAtmosphere, new string[]{"at"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.TechnicalAtmosphere, new string[]{"ат"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.TonneForcePerSquareCentimeter, new string[]{"tf/cm²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.TonneForcePerSquareMeter, new string[]{"tf/m²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.TonneForcePerSquareMillimeter, new string[]{"tf/mm²"}), + ("en-US", typeof(PressureUnit), (int)PressureUnit.Torr, new string[]{"torr"}), + ("ru-RU", typeof(PressureUnit), (int)PressureUnit.Torr, new string[]{"торр"}), + ("en-US", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.AtmospherePerSecond, new string[]{"atm/s"}), + ("ru-RU", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.AtmospherePerSecond, new string[]{"атм/с"}), + ("en-US", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.KilopascalPerSecond, new string[]{"kPa/s"}), + ("ru-RU", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.KilopascalPerSecond, new string[]{"кПа/с"}), + ("en-US", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.MegapascalPerSecond, new string[]{"MPa/s"}), + ("ru-RU", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.MegapascalPerSecond, new string[]{"МПа/с"}), + ("en-US", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.PascalPerSecond, new string[]{"Pa/s"}), + ("ru-RU", typeof(PressureChangeRateUnit), (int)PressureChangeRateUnit.PascalPerSecond, new string[]{"Па/с"}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.DecimalFraction, new string[]{""}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.PartPerBillion, new string[]{"ppb"}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.PartPerMillion, new string[]{"ppm"}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.PartPerThousand, new string[]{"‰"}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.PartPerTrillion, new string[]{"ppt"}), + ("en-US", typeof(RatioUnit), (int)RatioUnit.Percent, new string[]{"%"}), + ("en-US", typeof(ReactiveEnergyUnit), (int)ReactiveEnergyUnit.KilovoltampereReactiveHour, new string[]{"kvarh"}), + ("en-US", typeof(ReactiveEnergyUnit), (int)ReactiveEnergyUnit.MegavoltampereReactiveHour, new string[]{"Mvarh"}), + ("en-US", typeof(ReactiveEnergyUnit), (int)ReactiveEnergyUnit.VoltampereReactiveHour, new string[]{"varh"}), + ("en-US", typeof(ReactivePowerUnit), (int)ReactivePowerUnit.GigavoltampereReactive, new string[]{"Gvar"}), + ("en-US", typeof(ReactivePowerUnit), (int)ReactivePowerUnit.KilovoltampereReactive, new string[]{"kvar"}), + ("en-US", typeof(ReactivePowerUnit), (int)ReactivePowerUnit.MegavoltampereReactive, new string[]{"Mvar"}), + ("en-US", typeof(ReactivePowerUnit), (int)ReactivePowerUnit.VoltampereReactive, new string[]{"var"}), + ("en-US", typeof(RotationalAccelerationUnit), (int)RotationalAccelerationUnit.DegreePerSecondSquared, new string[]{"°/s²", "deg/s²"}), + ("en-US", typeof(RotationalAccelerationUnit), (int)RotationalAccelerationUnit.RadianPerSecondSquared, new string[]{"rad/s²"}), + ("en-US", typeof(RotationalAccelerationUnit), (int)RotationalAccelerationUnit.RevolutionPerMinutePerSecond, new string[]{"rpm/s"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.CentiradianPerSecond, new string[]{"crad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.CentiradianPerSecond, new string[]{"cрад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.DeciradianPerSecond, new string[]{"drad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.DeciradianPerSecond, new string[]{"dрад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.DegreePerMinute, new string[]{"°/min", "deg/min"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.DegreePerSecond, new string[]{"°/s", "deg/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.DegreePerSecond, new string[]{"°/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MicrodegreePerSecond, new string[]{"µ°/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MicrodegreePerSecond, new string[]{"µ°/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MicroradianPerSecond, new string[]{"µrad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MicroradianPerSecond, new string[]{"µрад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MillidegreePerSecond, new string[]{"m°/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MillidegreePerSecond, new string[]{"m°/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MilliradianPerSecond, new string[]{"mrad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.MilliradianPerSecond, new string[]{"mрад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.NanodegreePerSecond, new string[]{"n°/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.NanodegreePerSecond, new string[]{"n°/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.NanoradianPerSecond, new string[]{"nrad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.NanoradianPerSecond, new string[]{"nрад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RadianPerSecond, new string[]{"rad/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RadianPerSecond, new string[]{"рад/с"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RevolutionPerMinute, new string[]{"rpm", "r/min"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RevolutionPerMinute, new string[]{"об/мин"}), + ("en-US", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RevolutionPerSecond, new string[]{"r/s"}), + ("ru-RU", typeof(RotationalSpeedUnit), (int)RotationalSpeedUnit.RevolutionPerSecond, new string[]{"об/с"}), + ("en-US", typeof(RotationalStiffnessUnit), (int)RotationalStiffnessUnit.KilonewtonMeterPerRadian, new string[]{"kN·m/rad"}), + ("en-US", typeof(RotationalStiffnessUnit), (int)RotationalStiffnessUnit.MeganewtonMeterPerRadian, new string[]{"MN·m/rad"}), + ("en-US", typeof(RotationalStiffnessUnit), (int)RotationalStiffnessUnit.NewtonMeterPerRadian, new string[]{"N·m/rad", "Nm/rad"}), + ("en-US", typeof(RotationalStiffnessPerLengthUnit), (int)RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, new string[]{"kN·m/rad/m"}), + ("en-US", typeof(RotationalStiffnessPerLengthUnit), (int)RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, new string[]{"MN·m/rad/m"}), + ("en-US", typeof(RotationalStiffnessPerLengthUnit), (int)RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, new string[]{"N·m/rad/m", "Nm/rad/m"}), + ("en-US", typeof(SolidAngleUnit), (int)SolidAngleUnit.Steradian, new string[]{"sr"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.CaloriePerGram, new string[]{"cal/g"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.JoulePerKilogram, new string[]{"J/kg"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.KilocaloriePerGram, new string[]{"kcal/g"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.KilojoulePerKilogram, new string[]{"kJ/kg"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.KilowattHourPerKilogram, new string[]{"kWh/kg"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.MegajoulePerKilogram, new string[]{"MJ/kg"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.MegawattHourPerKilogram, new string[]{"MWh/kg"}), + ("en-US", typeof(SpecificEnergyUnit), (int)SpecificEnergyUnit.WattHourPerKilogram, new string[]{"Wh/kg"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.CaloriePerGramKelvin, new string[]{"cal/g.K"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, new string[]{"J/kg.C"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.JoulePerKilogramKelvin, new string[]{"J/kg.K"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.KilocaloriePerGramKelvin, new string[]{"kcal/g.K"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, new string[]{"kJ/kg.C"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.KilojoulePerKilogramKelvin, new string[]{"kJ/kg.K"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, new string[]{"MJ/kg.C"}), + ("en-US", typeof(SpecificEntropyUnit), (int)SpecificEntropyUnit.MegajoulePerKilogramKelvin, new string[]{"MJ/kg.K"}), + ("en-US", typeof(SpecificVolumeUnit), (int)SpecificVolumeUnit.CubicFootPerPound, new string[]{"ft³/lb"}), + ("en-US", typeof(SpecificVolumeUnit), (int)SpecificVolumeUnit.CubicMeterPerKilogram, new string[]{"m³/kg"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilogramForcePerCubicCentimeter, new string[]{"kgf/cm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilogramForcePerCubicMeter, new string[]{"kgf/m³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilogramForcePerCubicMillimeter, new string[]{"kgf/mm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilonewtonPerCubicCentimeter, new string[]{"kN/cm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilonewtonPerCubicMeter, new string[]{"kN/m³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilonewtonPerCubicMillimeter, new string[]{"kN/mm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilopoundForcePerCubicFoot, new string[]{"kipf/ft³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.KilopoundForcePerCubicInch, new string[]{"kipf/in³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.MeganewtonPerCubicMeter, new string[]{"MN/m³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.NewtonPerCubicCentimeter, new string[]{"N/cm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.NewtonPerCubicMeter, new string[]{"N/m³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.NewtonPerCubicMillimeter, new string[]{"N/mm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.PoundForcePerCubicFoot, new string[]{"lbf/ft³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.PoundForcePerCubicInch, new string[]{"lbf/in³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.TonneForcePerCubicCentimeter, new string[]{"tf/cm³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.TonneForcePerCubicMeter, new string[]{"tf/m³"}), + ("en-US", typeof(SpecificWeightUnit), (int)SpecificWeightUnit.TonneForcePerCubicMillimeter, new string[]{"tf/mm³"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.CentimeterPerHour, new string[]{"cm/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.CentimeterPerMinute, new string[]{"cm/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.CentimeterPerSecond, new string[]{"cm/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.DecimeterPerMinute, new string[]{"dm/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.DecimeterPerSecond, new string[]{"dm/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.FootPerHour, new string[]{"ft/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.FootPerMinute, new string[]{"ft/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.FootPerSecond, new string[]{"ft/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.InchPerHour, new string[]{"in/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.InchPerMinute, new string[]{"in/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.InchPerSecond, new string[]{"in/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.KilometerPerHour, new string[]{"km/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.KilometerPerMinute, new string[]{"km/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.KilometerPerSecond, new string[]{"km/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.Knot, new string[]{"kn", "kt", "knot", "knots"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MeterPerHour, new string[]{"m/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MeterPerMinute, new string[]{"m/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MeterPerSecond, new string[]{"m/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MicrometerPerMinute, new string[]{"µm/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MicrometerPerSecond, new string[]{"µm/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MilePerHour, new string[]{"mph"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MillimeterPerHour, new string[]{"mm/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MillimeterPerMinute, new string[]{"mm/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.MillimeterPerSecond, new string[]{"mm/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.NanometerPerMinute, new string[]{"nm/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.NanometerPerSecond, new string[]{"nm/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.UsSurveyFootPerHour, new string[]{"ftUS/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.UsSurveyFootPerMinute, new string[]{"ftUS/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.UsSurveyFootPerSecond, new string[]{"ftUS/s"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.YardPerHour, new string[]{"yd/h"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.YardPerMinute, new string[]{"yd/min"}), + ("en-US", typeof(SpeedUnit), (int)SpeedUnit.YardPerSecond, new string[]{"yd/s"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeCelsius, new string[]{"°C"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeDelisle, new string[]{"°De"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeFahrenheit, new string[]{"°F"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeNewton, new string[]{"°N"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeRankine, new string[]{"°R"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeReaumur, new string[]{"°Ré"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.DegreeRoemer, new string[]{"°Rø"}), + ("en-US", typeof(TemperatureUnit), (int)TemperatureUnit.Kelvin, new string[]{"K"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, new string[]{"c°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, new string[]{"da°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, new string[]{"d°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.DegreeCelsiusPerMinute, new string[]{"°C/min"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.DegreeCelsiusPerSecond, new string[]{"°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, new string[]{"h°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, new string[]{"k°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, new string[]{"µ°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, new string[]{"m°C/s"}), + ("en-US", typeof(TemperatureChangeRateUnit), (int)TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, new string[]{"n°C/s"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeCelsius, new string[]{"∆°C"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeDelisle, new string[]{"∆°De"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeFahrenheit, new string[]{"∆°F"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeNewton, new string[]{"∆°N"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeRankine, new string[]{"∆°R"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeReaumur, new string[]{"∆°Ré"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.DegreeRoemer, new string[]{"∆°Rø"}), + ("en-US", typeof(TemperatureDeltaUnit), (int)TemperatureDeltaUnit.Kelvin, new string[]{"∆K"}), + ("en-US", typeof(ThermalConductivityUnit), (int)ThermalConductivityUnit.BtuPerHourFootFahrenheit, new string[]{"BTU/h·ft·°F"}), + ("en-US", typeof(ThermalConductivityUnit), (int)ThermalConductivityUnit.WattPerMeterKelvin, new string[]{"W/m·K"}), + ("en-US", typeof(ThermalResistanceUnit), (int)ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, new string[]{"Hrft²°F/Btu"}), + ("en-US", typeof(ThermalResistanceUnit), (int)ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, new string[]{"cm²Hr°C/kcal"}), + ("en-US", typeof(ThermalResistanceUnit), (int)ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, new string[]{"cm²K/W"}), + ("en-US", typeof(ThermalResistanceUnit), (int)ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, new string[]{"m²°C/W"}), + ("en-US", typeof(ThermalResistanceUnit), (int)ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, new string[]{"m²K/kW"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilogramForceCentimeter, new string[]{"kgf·cm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilogramForceMeter, new string[]{"kgf·m"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilogramForceMillimeter, new string[]{"kgf·mm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilonewtonCentimeter, new string[]{"kN·cm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilonewtonMeter, new string[]{"kN·m"}), + ("ru-RU", typeof(TorqueUnit), (int)TorqueUnit.KilonewtonMeter, new string[]{"кН·м"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilonewtonMillimeter, new string[]{"kN·mm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilopoundForceFoot, new string[]{"kipf·ft"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.KilopoundForceInch, new string[]{"kipf·in"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.MeganewtonCentimeter, new string[]{"MN·cm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.MeganewtonMeter, new string[]{"MN·m"}), + ("ru-RU", typeof(TorqueUnit), (int)TorqueUnit.MeganewtonMeter, new string[]{"МН·м"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.MeganewtonMillimeter, new string[]{"MN·mm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.MegapoundForceFoot, new string[]{"Mlbf·ft"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.MegapoundForceInch, new string[]{"Mlbf·in"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.NewtonCentimeter, new string[]{"N·cm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.NewtonMeter, new string[]{"N·m"}), + ("ru-RU", typeof(TorqueUnit), (int)TorqueUnit.NewtonMeter, new string[]{"Н·м"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.NewtonMillimeter, new string[]{"N·mm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.PoundForceFoot, new string[]{"lbf·ft"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.PoundForceInch, new string[]{"lbf·in"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.TonneForceCentimeter, new string[]{"tf·cm"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.TonneForceMeter, new string[]{"tf·m"}), + ("en-US", typeof(TorqueUnit), (int)TorqueUnit.TonneForceMillimeter, new string[]{"tf·mm"}), + ("en-US", typeof(VitaminAUnit), (int)VitaminAUnit.InternationalUnit, new string[]{"IU"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.AuTablespoon, new string[]{""}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.AuTablespoon, new string[]{""}), + ("nb-NO", typeof(VolumeUnit), (int)VolumeUnit.AuTablespoon, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Centiliter, new string[]{"cl"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Centiliter, new string[]{"сл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicCentimeter, new string[]{"cm³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicCentimeter, new string[]{"см³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicDecimeter, new string[]{"dm³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicDecimeter, new string[]{"дм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicFoot, new string[]{"ft³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicFoot, new string[]{"фут³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicInch, new string[]{"in³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicInch, new string[]{"дюйм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicKilometer, new string[]{"km³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicKilometer, new string[]{"км³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicMeter, new string[]{"m³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicMeter, new string[]{"м³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicMicrometer, new string[]{"µm³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicMicrometer, new string[]{"мкм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicMile, new string[]{"mi³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicMile, new string[]{"миля³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicMillimeter, new string[]{"mm³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicMillimeter, new string[]{"мм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.CubicYard, new string[]{"yd³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.CubicYard, new string[]{"ярд³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Deciliter, new string[]{"dl"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Deciliter, new string[]{"дл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.HectocubicFoot, new string[]{"hft³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.HectocubicFoot, new string[]{"hфут³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.HectocubicMeter, new string[]{"hm³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.HectocubicMeter, new string[]{"hм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Hectoliter, new string[]{"hl"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Hectoliter, new string[]{"гл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.ImperialBeerBarrel, new string[]{"bl (imp.)"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.ImperialGallon, new string[]{"gal (imp.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.ImperialGallon, new string[]{"Английский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.ImperialOunce, new string[]{"oz (imp.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.ImperialOunce, new string[]{"Английская унция"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.KilocubicFoot, new string[]{"kft³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.KilocubicFoot, new string[]{"kфут³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.KilocubicMeter, new string[]{"km³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.KilocubicMeter, new string[]{"kм³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.KiloimperialGallon, new string[]{"kgal (imp.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.KiloimperialGallon, new string[]{"kАнглийский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Kiloliter, new string[]{"kl"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Kiloliter, new string[]{"кл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.KilousGallon, new string[]{"kgal (U.S.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.KilousGallon, new string[]{"kАмериканский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Liter, new string[]{"l"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Liter, new string[]{"л"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.MegacubicFoot, new string[]{"Mft³"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.MegacubicFoot, new string[]{"Mфут³"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.MegaimperialGallon, new string[]{"Mgal (imp.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.MegaimperialGallon, new string[]{"MАнглийский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.MegausGallon, new string[]{"Mgal (U.S.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.MegausGallon, new string[]{"MАмериканский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.MetricCup, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.MetricTeaspoon, new string[]{"tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.MetricTeaspoon, new string[]{""}), + ("nb-NO", typeof(VolumeUnit), (int)VolumeUnit.MetricTeaspoon, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Microliter, new string[]{"µl"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Microliter, new string[]{"мкл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.Milliliter, new string[]{"ml"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.Milliliter, new string[]{"мл"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.OilBarrel, new string[]{"bbl"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UkTablespoon, new string[]{""}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.UkTablespoon, new string[]{""}), + ("nb-NO", typeof(VolumeUnit), (int)VolumeUnit.UkTablespoon, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsBeerBarrel, new string[]{"bl (U.S.)"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsCustomaryCup, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsGallon, new string[]{"gal (U.S.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.UsGallon, new string[]{"Американский галлон"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsLegalCup, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsOunce, new string[]{"oz (U.S.)"}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.UsOunce, new string[]{"Американская унция"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsPint, new string[]{"pt (U.S.)"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsQuart, new string[]{"qt (U.S.)"}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsTablespoon, new string[]{""}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.UsTablespoon, new string[]{""}), + ("nb-NO", typeof(VolumeUnit), (int)VolumeUnit.UsTablespoon, new string[]{""}), + ("en-US", typeof(VolumeUnit), (int)VolumeUnit.UsTeaspoon, new string[]{""}), + ("ru-RU", typeof(VolumeUnit), (int)VolumeUnit.UsTeaspoon, new string[]{""}), + ("nb-NO", typeof(VolumeUnit), (int)VolumeUnit.UsTeaspoon, new string[]{""}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CentiliterPerMinute, new string[]{"cLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicDecimeterPerMinute, new string[]{"dm³/min"}), + ("ru-RU", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicDecimeterPerMinute, new string[]{"дм³/мин"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicFootPerHour, new string[]{"ft³/h", "cf/hr"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicFootPerMinute, new string[]{"ft³/min"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicFootPerSecond, new string[]{"ft³/s"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMeterPerHour, new string[]{"m³/h"}), + ("ru-RU", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMeterPerHour, new string[]{"м³/ч"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMeterPerMinute, new string[]{"m³/min"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMeterPerSecond, new string[]{"m³/s"}), + ("ru-RU", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMeterPerSecond, new string[]{"м³/с"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMillimeterPerSecond, new string[]{"mm³/s"}), + ("ru-RU", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicMillimeterPerSecond, new string[]{"мм³/с"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicYardPerHour, new string[]{"yd³/h"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicYardPerMinute, new string[]{"yd³/min"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.CubicYardPerSecond, new string[]{"yd³/s"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.DeciliterPerMinute, new string[]{"dLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.KiloliterPerMinute, new string[]{"kLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.KilousGallonsPerMinute, new string[]{"kgal (U.S.)/min", "KGPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.LiterPerHour, new string[]{"LPH"}), + ("ru-RU", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.LiterPerHour, new string[]{"л/ч"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.LiterPerMinute, new string[]{"LPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.LiterPerSecond, new string[]{"LPS"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.MicroliterPerMinute, new string[]{"µLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.MilliliterPerMinute, new string[]{"mLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.MillionUsGallonsPerDay, new string[]{"MGD"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.NanoliterPerMinute, new string[]{"nLPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.OilBarrelPerDay, new string[]{"bbl/d", "BOPD"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.OilBarrelPerHour, new string[]{"bbl/hr", "bph"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.OilBarrelPerMinute, new string[]{"bbl/min", "bpm"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.UsGallonPerHour, new string[]{"gal (U.S.)/h"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.UsGallonPerMinute, new string[]{"gal (U.S.)/min", "GPM"}), + ("en-US", typeof(VolumeFlowUnit), (int)VolumeFlowUnit.UsGallonPerSecond, new string[]{"gal (U.S.)/s"}), + }; + } +} diff --git a/UnitsNet/GeneratedCode/UnitSystem.Default.g.cs b/UnitsNet/GeneratedCode/UnitSystem.Default.g.cs deleted file mode 100644 index 9c26a8f8af..0000000000 --- a/UnitsNet/GeneratedCode/UnitSystem.Default.g.cs +++ /dev/null @@ -1,4924 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.Collections.Generic; -using System.Collections.ObjectModel; -using UnitsNet.I18n; -using UnitsNet.Units; - -// ReSharper disable RedundantCommaInArrayInitializer -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - public sealed partial class UnitSystem - { - private static readonly ReadOnlyCollection DefaultLocalizations - = new ReadOnlyCollection(new List - { - new UnitLocalization(typeof (AccelerationUnit), - new[] - { - new CulturesForEnumValue((int) AccelerationUnit.CentimeterPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "cm/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.DecimeterPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "dm/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.FootPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "ft/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.InchPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "in/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.KilometerPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "km/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.KnotPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "kn/h"), - }), - new CulturesForEnumValue((int) AccelerationUnit.KnotPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kn/min"), - }), - new CulturesForEnumValue((int) AccelerationUnit.KnotPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kn/s"), - }), - new CulturesForEnumValue((int) AccelerationUnit.MeterPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "m/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.MicrometerPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "µm/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.MillimeterPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "mm/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.NanometerPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "nm/s²"), - }), - new CulturesForEnumValue((int) AccelerationUnit.StandardGravity, - new[] - { - new AbbreviationsForCulture("en-US", "g"), - }), - }), - new UnitLocalization(typeof (AmountOfSubstanceUnit), - new[] - { - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Centimole, - new[] - { - new AbbreviationsForCulture("en-US", "cmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.CentipoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "clbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Decimole, - new[] - { - new AbbreviationsForCulture("en-US", "dmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.DecipoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "dlbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Kilomole, - new[] - { - new AbbreviationsForCulture("en-US", "kmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.KilopoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "klbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Megamole, - new[] - { - new AbbreviationsForCulture("en-US", "Mmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Micromole, - new[] - { - new AbbreviationsForCulture("en-US", "µmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.MicropoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "µlbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Millimole, - new[] - { - new AbbreviationsForCulture("en-US", "mmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.MillipoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "mlbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Mole, - new[] - { - new AbbreviationsForCulture("en-US", "mol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.Nanomole, - new[] - { - new AbbreviationsForCulture("en-US", "nmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.NanopoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "nlbmol"), - }), - new CulturesForEnumValue((int) AmountOfSubstanceUnit.PoundMole, - new[] - { - new AbbreviationsForCulture("en-US", "lbmol"), - }), - }), - new UnitLocalization(typeof (AmplitudeRatioUnit), - new[] - { - new CulturesForEnumValue((int) AmplitudeRatioUnit.DecibelMicrovolt, - new[] - { - new AbbreviationsForCulture("en-US", "dBµV"), - }), - new CulturesForEnumValue((int) AmplitudeRatioUnit.DecibelMillivolt, - new[] - { - new AbbreviationsForCulture("en-US", "dBmV"), - }), - new CulturesForEnumValue((int) AmplitudeRatioUnit.DecibelUnloaded, - new[] - { - new AbbreviationsForCulture("en-US", "dBu"), - }), - new CulturesForEnumValue((int) AmplitudeRatioUnit.DecibelVolt, - new[] - { - new AbbreviationsForCulture("en-US", "dBV"), - }), - }), - new UnitLocalization(typeof (AngleUnit), - new[] - { - new CulturesForEnumValue((int) AngleUnit.Arcminute, - new[] - { - new AbbreviationsForCulture("en-US", "'", "arcmin", "amin", "min"), - }), - new CulturesForEnumValue((int) AngleUnit.Arcsecond, - new[] - { - new AbbreviationsForCulture("en-US", "″", "arcsec", "asec", "sec"), - }), - new CulturesForEnumValue((int) AngleUnit.Centiradian, - new[] - { - new AbbreviationsForCulture("en-US", "crad"), - new AbbreviationsForCulture("ru-RU", "cрад"), - }), - new CulturesForEnumValue((int) AngleUnit.Deciradian, - new[] - { - new AbbreviationsForCulture("en-US", "drad"), - new AbbreviationsForCulture("ru-RU", "dрад"), - }), - new CulturesForEnumValue((int) AngleUnit.Degree, - new[] - { - new AbbreviationsForCulture("en-US", "°", "deg"), - new AbbreviationsForCulture("ru-RU", "°"), - }), - new CulturesForEnumValue((int) AngleUnit.Gradian, - new[] - { - new AbbreviationsForCulture("en-US", "g"), - new AbbreviationsForCulture("ru-RU", "g"), - }), - new CulturesForEnumValue((int) AngleUnit.Microdegree, - new[] - { - new AbbreviationsForCulture("en-US", "µ°"), - new AbbreviationsForCulture("ru-RU", "µ°"), - }), - new CulturesForEnumValue((int) AngleUnit.Microradian, - new[] - { - new AbbreviationsForCulture("en-US", "µrad"), - new AbbreviationsForCulture("ru-RU", "µрад"), - }), - new CulturesForEnumValue((int) AngleUnit.Millidegree, - new[] - { - new AbbreviationsForCulture("en-US", "m°"), - new AbbreviationsForCulture("ru-RU", "m°"), - }), - new CulturesForEnumValue((int) AngleUnit.Milliradian, - new[] - { - new AbbreviationsForCulture("en-US", "mrad"), - new AbbreviationsForCulture("ru-RU", "mрад"), - }), - new CulturesForEnumValue((int) AngleUnit.Nanodegree, - new[] - { - new AbbreviationsForCulture("en-US", "n°"), - new AbbreviationsForCulture("ru-RU", "n°"), - }), - new CulturesForEnumValue((int) AngleUnit.Nanoradian, - new[] - { - new AbbreviationsForCulture("en-US", "nrad"), - new AbbreviationsForCulture("ru-RU", "nрад"), - }), - new CulturesForEnumValue((int) AngleUnit.Radian, - new[] - { - new AbbreviationsForCulture("en-US", "rad"), - new AbbreviationsForCulture("ru-RU", "рад"), - }), - new CulturesForEnumValue((int) AngleUnit.Revolution, - new[] - { - new AbbreviationsForCulture("en-US", "r"), - new AbbreviationsForCulture("ru-RU", "r"), - }), - }), - new UnitLocalization(typeof (ApparentEnergyUnit), - new[] - { - new CulturesForEnumValue((int) ApparentEnergyUnit.KilovoltampereHour, - new[] - { - new AbbreviationsForCulture("en-US", "kVAh"), - }), - new CulturesForEnumValue((int) ApparentEnergyUnit.MegavoltampereHour, - new[] - { - new AbbreviationsForCulture("en-US", "MVAh"), - }), - new CulturesForEnumValue((int) ApparentEnergyUnit.VoltampereHour, - new[] - { - new AbbreviationsForCulture("en-US", "VAh"), - }), - }), - new UnitLocalization(typeof (ApparentPowerUnit), - new[] - { - new CulturesForEnumValue((int) ApparentPowerUnit.Gigavoltampere, - new[] - { - new AbbreviationsForCulture("en-US", "GVA"), - }), - new CulturesForEnumValue((int) ApparentPowerUnit.Kilovoltampere, - new[] - { - new AbbreviationsForCulture("en-US", "kVA"), - }), - new CulturesForEnumValue((int) ApparentPowerUnit.Megavoltampere, - new[] - { - new AbbreviationsForCulture("en-US", "MVA"), - }), - new CulturesForEnumValue((int) ApparentPowerUnit.Voltampere, - new[] - { - new AbbreviationsForCulture("en-US", "VA"), - }), - }), - new UnitLocalization(typeof (AreaUnit), - new[] - { - new CulturesForEnumValue((int) AreaUnit.Acre, - new[] - { - new AbbreviationsForCulture("en-US", "ac"), - }), - new CulturesForEnumValue((int) AreaUnit.Hectare, - new[] - { - new AbbreviationsForCulture("en-US", "ha"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "cm²"), - new AbbreviationsForCulture("ru-RU", "см²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "dm²"), - new AbbreviationsForCulture("ru-RU", "дм²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "ft²"), - new AbbreviationsForCulture("ru-RU", "фут²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "in²"), - new AbbreviationsForCulture("ru-RU", "дюйм²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareKilometer, - new[] - { - new AbbreviationsForCulture("en-US", "km²"), - new AbbreviationsForCulture("ru-RU", "км²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "m²"), - new AbbreviationsForCulture("ru-RU", "м²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareMicrometer, - new[] - { - new AbbreviationsForCulture("en-US", "µm²"), - new AbbreviationsForCulture("ru-RU", "мкм²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareMile, - new[] - { - new AbbreviationsForCulture("en-US", "mi²"), - new AbbreviationsForCulture("ru-RU", "миля²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mm²"), - new AbbreviationsForCulture("ru-RU", "мм²"), - }), - new CulturesForEnumValue((int) AreaUnit.SquareYard, - new[] - { - new AbbreviationsForCulture("en-US", "yd²"), - new AbbreviationsForCulture("ru-RU", "ярд²"), - }), - new CulturesForEnumValue((int) AreaUnit.UsSurveySquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "ft² (US)"), - }), - }), - new UnitLocalization(typeof (AreaDensityUnit), - new[] - { - new CulturesForEnumValue((int) AreaDensityUnit.KilogramPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg/m²"), - }), - }), - new UnitLocalization(typeof (AreaMomentOfInertiaUnit), - new[] - { - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.CentimeterToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "cm⁴", "cm^4"), - }), - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.DecimeterToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "dm⁴", "dm^4"), - }), - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.FootToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "ft⁴", "ft^4"), - }), - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.InchToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "in⁴", "in^4"), - }), - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.MeterToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "m⁴", "m^4"), - }), - new CulturesForEnumValue((int) AreaMomentOfInertiaUnit.MillimeterToTheFourth, - new[] - { - new AbbreviationsForCulture("en-US", "mm⁴", "mm^4"), - }), - }), - new UnitLocalization(typeof (BitRateUnit), - new[] - { - new CulturesForEnumValue((int) BitRateUnit.BitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "bit/s", "bps"), - }), - new CulturesForEnumValue((int) BitRateUnit.BytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "B/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.ExabitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Ebit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.ExabytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "EB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.ExbibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Eibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.ExbibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "EiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.GibibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Gibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.GibibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "GiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.GigabitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Gbit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.GigabytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "GB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.KibibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Kibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.KibibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "KiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.KilobitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kbit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.KilobytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.MebibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Mibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.MebibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "MiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.MegabitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Mbit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.MegabytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "MB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.PebibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Pibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.PebibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "PiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.PetabitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Pbit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.PetabytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "PB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.TebibitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Tibit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.TebibytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "TiB/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.TerabitPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Tbit/s"), - }), - new CulturesForEnumValue((int) BitRateUnit.TerabytePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "TB/s"), - }), - }), - new UnitLocalization(typeof (BrakeSpecificFuelConsumptionUnit), - new[] - { - new CulturesForEnumValue((int) BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, - new[] - { - new AbbreviationsForCulture("en-US", "g/kWh"), - }), - new CulturesForEnumValue((int) BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, - new[] - { - new AbbreviationsForCulture("en-US", "kg/J"), - }), - new CulturesForEnumValue((int) BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, - new[] - { - new AbbreviationsForCulture("en-US", "lb/hph"), - }), - }), - new UnitLocalization(typeof (CapacitanceUnit), - new[] - { - new CulturesForEnumValue((int) CapacitanceUnit.Farad, - new[] - { - new AbbreviationsForCulture("en-US", "F"), - }), - new CulturesForEnumValue((int) CapacitanceUnit.Microfarad, - new[] - { - new AbbreviationsForCulture("en-US", "µF"), - }), - new CulturesForEnumValue((int) CapacitanceUnit.Millifarad, - new[] - { - new AbbreviationsForCulture("en-US", "mF"), - }), - new CulturesForEnumValue((int) CapacitanceUnit.Nanofarad, - new[] - { - new AbbreviationsForCulture("en-US", "nF"), - }), - new CulturesForEnumValue((int) CapacitanceUnit.Picofarad, - new[] - { - new AbbreviationsForCulture("en-US", "pF"), - }), - }), - new UnitLocalization(typeof (CoefficientOfThermalExpansionUnit), - new[] - { - new CulturesForEnumValue((int) CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "°C⁻¹", "1/°C"), - }), - new CulturesForEnumValue((int) CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, - new[] - { - new AbbreviationsForCulture("en-US", "°F⁻¹", "1/°F"), - }), - new CulturesForEnumValue((int) CoefficientOfThermalExpansionUnit.InverseKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "K⁻¹", "1/K"), - }), - }), - new UnitLocalization(typeof (DensityUnit), - new[] - { - new CulturesForEnumValue((int) DensityUnit.CentigramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "cg/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.CentigramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "cg/L"), - }), - new CulturesForEnumValue((int) DensityUnit.CentigramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "cg/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.DecigramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "dg/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.DecigramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "dg/L"), - }), - new CulturesForEnumValue((int) DensityUnit.DecigramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "dg/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "g/cm³"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "g/m³"), - new AbbreviationsForCulture("ru-RU", "г/м³"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "g/mm³"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "g/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "g/L"), - }), - new CulturesForEnumValue((int) DensityUnit.GramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "g/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.KilogramPerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg/cm³"), - }), - new CulturesForEnumValue((int) DensityUnit.KilogramPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg/m³"), - new AbbreviationsForCulture("ru-RU", "kг/м³"), - }), - new CulturesForEnumValue((int) DensityUnit.KilogramPerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg/mm³"), - }), - new CulturesForEnumValue((int) DensityUnit.KilopoundPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kip/ft³"), - }), - new CulturesForEnumValue((int) DensityUnit.KilopoundPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "kip/in³"), - }), - new CulturesForEnumValue((int) DensityUnit.MicrogramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "µg/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.MicrogramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "µg/L"), - }), - new CulturesForEnumValue((int) DensityUnit.MicrogramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "µg/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.MilligramPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mg/m³"), - new AbbreviationsForCulture("ru-RU", "mг/м³"), - }), - new CulturesForEnumValue((int) DensityUnit.MilligramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "mg/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.MilligramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "mg/L"), - }), - new CulturesForEnumValue((int) DensityUnit.MilligramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "mg/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.NanogramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "ng/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.NanogramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "ng/L"), - }), - new CulturesForEnumValue((int) DensityUnit.NanogramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "ng/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.PicogramPerDeciliter, - new[] - { - new AbbreviationsForCulture("en-US", "pg/dl"), - }), - new CulturesForEnumValue((int) DensityUnit.PicogramPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "pg/L"), - }), - new CulturesForEnumValue((int) DensityUnit.PicogramPerMilliliter, - new[] - { - new AbbreviationsForCulture("en-US", "pg/ml"), - }), - new CulturesForEnumValue((int) DensityUnit.PoundPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lb/ft³"), - }), - new CulturesForEnumValue((int) DensityUnit.PoundPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "lb/in³"), - }), - new CulturesForEnumValue((int) DensityUnit.PoundPerImperialGallon, - new[] - { - new AbbreviationsForCulture("en-US", "ppg (imp.)"), - }), - new CulturesForEnumValue((int) DensityUnit.PoundPerUSGallon, - new[] - { - new AbbreviationsForCulture("en-US", "ppg (U.S.)"), - }), - new CulturesForEnumValue((int) DensityUnit.SlugPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "slug/ft³"), - }), - new CulturesForEnumValue((int) DensityUnit.TonnePerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "t/cm³"), - }), - new CulturesForEnumValue((int) DensityUnit.TonnePerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "t/m³"), - }), - new CulturesForEnumValue((int) DensityUnit.TonnePerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "t/mm³"), - }), - }), - new UnitLocalization(typeof (DurationUnit), - new[] - { - new CulturesForEnumValue((int) DurationUnit.Day, - new[] - { - new AbbreviationsForCulture("en-US", "d", "day", "days"), - new AbbreviationsForCulture("ru-RU", "д"), - }), - new CulturesForEnumValue((int) DurationUnit.Hour, - new[] - { - new AbbreviationsForCulture("en-US", "h", "hr", "hrs", "hour", "hours"), - new AbbreviationsForCulture("ru-RU", "ч"), - }), - new CulturesForEnumValue((int) DurationUnit.Microsecond, - new[] - { - new AbbreviationsForCulture("en-US", "µs"), - new AbbreviationsForCulture("ru-RU", "мкс"), - }), - new CulturesForEnumValue((int) DurationUnit.Millisecond, - new[] - { - new AbbreviationsForCulture("en-US", "ms"), - new AbbreviationsForCulture("ru-RU", "мс"), - }), - new CulturesForEnumValue((int) DurationUnit.Minute, - new[] - { - new AbbreviationsForCulture("en-US", "m", "min", "minute", "minutes"), - new AbbreviationsForCulture("ru-RU", "мин"), - }), - new CulturesForEnumValue((int) DurationUnit.Month, - new[] - { - new AbbreviationsForCulture("en-US", "mo", "month", "months"), - new AbbreviationsForCulture("ru-RU", "месяц"), - }), - new CulturesForEnumValue((int) DurationUnit.Month30, - new[] - { - new AbbreviationsForCulture("en-US", "mo", "month", "months"), - new AbbreviationsForCulture("ru-RU", "месяц"), - }), - new CulturesForEnumValue((int) DurationUnit.Nanosecond, - new[] - { - new AbbreviationsForCulture("en-US", "ns"), - new AbbreviationsForCulture("ru-RU", "нс"), - }), - new CulturesForEnumValue((int) DurationUnit.Second, - new[] - { - new AbbreviationsForCulture("en-US", "s", "sec", "secs", "second", "seconds"), - new AbbreviationsForCulture("ru-RU", "с"), - }), - new CulturesForEnumValue((int) DurationUnit.Week, - new[] - { - new AbbreviationsForCulture("en-US", "wk", "week", "weeks"), - new AbbreviationsForCulture("ru-RU", "мин"), - }), - new CulturesForEnumValue((int) DurationUnit.Year, - new[] - { - new AbbreviationsForCulture("en-US", "yr", "year", "years"), - new AbbreviationsForCulture("ru-RU", "год"), - }), - new CulturesForEnumValue((int) DurationUnit.Year365, - new[] - { - new AbbreviationsForCulture("en-US", "yr", "year", "years"), - new AbbreviationsForCulture("ru-RU", "год"), - }), - }), - new UnitLocalization(typeof (DynamicViscosityUnit), - new[] - { - new CulturesForEnumValue((int) DynamicViscosityUnit.Centipoise, - new[] - { - new AbbreviationsForCulture("en-US", "cP"), - }), - new CulturesForEnumValue((int) DynamicViscosityUnit.MicropascalSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µPaS"), - }), - new CulturesForEnumValue((int) DynamicViscosityUnit.MillipascalSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mPaS"), - }), - new CulturesForEnumValue((int) DynamicViscosityUnit.NewtonSecondPerMeterSquared, - new[] - { - new AbbreviationsForCulture("en-US", "Ns/m²"), - }), - new CulturesForEnumValue((int) DynamicViscosityUnit.PascalSecond, - new[] - { - new AbbreviationsForCulture("en-US", "PaS"), - }), - new CulturesForEnumValue((int) DynamicViscosityUnit.Poise, - new[] - { - new AbbreviationsForCulture("en-US", "P"), - }), - }), - new UnitLocalization(typeof (ElectricAdmittanceUnit), - new[] - { - new CulturesForEnumValue((int) ElectricAdmittanceUnit.Microsiemens, - new[] - { - new AbbreviationsForCulture("en-US", "µS"), - }), - new CulturesForEnumValue((int) ElectricAdmittanceUnit.Millisiemens, - new[] - { - new AbbreviationsForCulture("en-US", "mS"), - }), - new CulturesForEnumValue((int) ElectricAdmittanceUnit.Nanosiemens, - new[] - { - new AbbreviationsForCulture("en-US", "nS"), - }), - new CulturesForEnumValue((int) ElectricAdmittanceUnit.Siemens, - new[] - { - new AbbreviationsForCulture("en-US", "S"), - }), - }), - new UnitLocalization(typeof (ElectricChargeUnit), - new[] - { - new CulturesForEnumValue((int) ElectricChargeUnit.Coulomb, - new[] - { - new AbbreviationsForCulture("en-US", "C"), - }), - }), - new UnitLocalization(typeof (ElectricChargeDensityUnit), - new[] - { - new CulturesForEnumValue((int) ElectricChargeDensityUnit.CoulombPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "C/m³"), - }), - }), - new UnitLocalization(typeof (ElectricConductanceUnit), - new[] - { - new CulturesForEnumValue((int) ElectricConductanceUnit.Microsiemens, - new[] - { - new AbbreviationsForCulture("en-US", "µS"), - }), - new CulturesForEnumValue((int) ElectricConductanceUnit.Millisiemens, - new[] - { - new AbbreviationsForCulture("en-US", "mS"), - }), - new CulturesForEnumValue((int) ElectricConductanceUnit.Siemens, - new[] - { - new AbbreviationsForCulture("en-US", "S"), - }), - }), - new UnitLocalization(typeof (ElectricConductivityUnit), - new[] - { - new CulturesForEnumValue((int) ElectricConductivityUnit.SiemensPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "S/m"), - }), - }), - new UnitLocalization(typeof (ElectricCurrentUnit), - new[] - { - new CulturesForEnumValue((int) ElectricCurrentUnit.Ampere, - new[] - { - new AbbreviationsForCulture("en-US", "A"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Centiampere, - new[] - { - new AbbreviationsForCulture("en-US", "cA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Kiloampere, - new[] - { - new AbbreviationsForCulture("en-US", "kA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Megaampere, - new[] - { - new AbbreviationsForCulture("en-US", "MA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Microampere, - new[] - { - new AbbreviationsForCulture("en-US", "µA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Milliampere, - new[] - { - new AbbreviationsForCulture("en-US", "mA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Nanoampere, - new[] - { - new AbbreviationsForCulture("en-US", "nA"), - }), - new CulturesForEnumValue((int) ElectricCurrentUnit.Picoampere, - new[] - { - new AbbreviationsForCulture("en-US", "pA"), - }), - }), - new UnitLocalization(typeof (ElectricCurrentDensityUnit), - new[] - { - new CulturesForEnumValue((int) ElectricCurrentDensityUnit.AmperePerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "A/m²"), - }), - }), - new UnitLocalization(typeof (ElectricCurrentGradientUnit), - new[] - { - new CulturesForEnumValue((int) ElectricCurrentGradientUnit.AmperePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "A/s"), - }), - }), - new UnitLocalization(typeof (ElectricFieldUnit), - new[] - { - new CulturesForEnumValue((int) ElectricFieldUnit.VoltPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "V/m"), - }), - }), - new UnitLocalization(typeof (ElectricInductanceUnit), - new[] - { - new CulturesForEnumValue((int) ElectricInductanceUnit.Henry, - new[] - { - new AbbreviationsForCulture("en-US", "H"), - }), - new CulturesForEnumValue((int) ElectricInductanceUnit.Microhenry, - new[] - { - new AbbreviationsForCulture("en-US", "µH"), - }), - new CulturesForEnumValue((int) ElectricInductanceUnit.Millihenry, - new[] - { - new AbbreviationsForCulture("en-US", "mH"), - }), - new CulturesForEnumValue((int) ElectricInductanceUnit.Nanohenry, - new[] - { - new AbbreviationsForCulture("en-US", "nH"), - }), - }), - new UnitLocalization(typeof (ElectricPotentialUnit), - new[] - { - new CulturesForEnumValue((int) ElectricPotentialUnit.Kilovolt, - new[] - { - new AbbreviationsForCulture("en-US", "kV"), - new AbbreviationsForCulture("ru-RU", "kВ"), - }), - new CulturesForEnumValue((int) ElectricPotentialUnit.Megavolt, - new[] - { - new AbbreviationsForCulture("en-US", "MV"), - new AbbreviationsForCulture("ru-RU", "MВ"), - }), - new CulturesForEnumValue((int) ElectricPotentialUnit.Microvolt, - new[] - { - new AbbreviationsForCulture("en-US", "µV"), - new AbbreviationsForCulture("ru-RU", "µВ"), - }), - new CulturesForEnumValue((int) ElectricPotentialUnit.Millivolt, - new[] - { - new AbbreviationsForCulture("en-US", "mV"), - new AbbreviationsForCulture("ru-RU", "mВ"), - }), - new CulturesForEnumValue((int) ElectricPotentialUnit.Volt, - new[] - { - new AbbreviationsForCulture("en-US", "V"), - new AbbreviationsForCulture("ru-RU", "В"), - }), - }), - new UnitLocalization(typeof (ElectricPotentialAcUnit), - new[] - { - new CulturesForEnumValue((int) ElectricPotentialAcUnit.KilovoltAc, - new[] - { - new AbbreviationsForCulture("en-US", "kVac"), - }), - new CulturesForEnumValue((int) ElectricPotentialAcUnit.MegavoltAc, - new[] - { - new AbbreviationsForCulture("en-US", "MVac"), - }), - new CulturesForEnumValue((int) ElectricPotentialAcUnit.MicrovoltAc, - new[] - { - new AbbreviationsForCulture("en-US", "µVac"), - }), - new CulturesForEnumValue((int) ElectricPotentialAcUnit.MillivoltAc, - new[] - { - new AbbreviationsForCulture("en-US", "mVac"), - }), - new CulturesForEnumValue((int) ElectricPotentialAcUnit.VoltAc, - new[] - { - new AbbreviationsForCulture("en-US", "Vac"), - }), - }), - new UnitLocalization(typeof (ElectricPotentialDcUnit), - new[] - { - new CulturesForEnumValue((int) ElectricPotentialDcUnit.KilovoltDc, - new[] - { - new AbbreviationsForCulture("en-US", "kVdc"), - }), - new CulturesForEnumValue((int) ElectricPotentialDcUnit.MegavoltDc, - new[] - { - new AbbreviationsForCulture("en-US", "MVdc"), - }), - new CulturesForEnumValue((int) ElectricPotentialDcUnit.MicrovoltDc, - new[] - { - new AbbreviationsForCulture("en-US", "µVdc"), - }), - new CulturesForEnumValue((int) ElectricPotentialDcUnit.MillivoltDc, - new[] - { - new AbbreviationsForCulture("en-US", "mVdc"), - }), - new CulturesForEnumValue((int) ElectricPotentialDcUnit.VoltDc, - new[] - { - new AbbreviationsForCulture("en-US", "Vdc"), - }), - }), - new UnitLocalization(typeof (ElectricResistanceUnit), - new[] - { - new CulturesForEnumValue((int) ElectricResistanceUnit.Gigaohm, - new[] - { - new AbbreviationsForCulture("en-US", "GΩ"), - }), - new CulturesForEnumValue((int) ElectricResistanceUnit.Kiloohm, - new[] - { - new AbbreviationsForCulture("en-US", "kΩ"), - }), - new CulturesForEnumValue((int) ElectricResistanceUnit.Megaohm, - new[] - { - new AbbreviationsForCulture("en-US", "MΩ"), - }), - new CulturesForEnumValue((int) ElectricResistanceUnit.Milliohm, - new[] - { - new AbbreviationsForCulture("en-US", "mΩ"), - }), - new CulturesForEnumValue((int) ElectricResistanceUnit.Ohm, - new[] - { - new AbbreviationsForCulture("en-US", "Ω"), - }), - }), - new UnitLocalization(typeof (ElectricResistivityUnit), - new[] - { - new CulturesForEnumValue((int) ElectricResistivityUnit.MicroohmMeter, - new[] - { - new AbbreviationsForCulture("en-US", "µΩ·m"), - }), - new CulturesForEnumValue((int) ElectricResistivityUnit.MilliohmMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mΩ·m"), - }), - new CulturesForEnumValue((int) ElectricResistivityUnit.NanoohmMeter, - new[] - { - new AbbreviationsForCulture("en-US", "nΩ·m"), - }), - new CulturesForEnumValue((int) ElectricResistivityUnit.OhmMeter, - new[] - { - new AbbreviationsForCulture("en-US", "Ω·m"), - }), - }), - new UnitLocalization(typeof (EnergyUnit), - new[] - { - new CulturesForEnumValue((int) EnergyUnit.BritishThermalUnit, - new[] - { - new AbbreviationsForCulture("en-US", "BTU"), - }), - new CulturesForEnumValue((int) EnergyUnit.Calorie, - new[] - { - new AbbreviationsForCulture("en-US", "cal"), - }), - new CulturesForEnumValue((int) EnergyUnit.DecathermEc, - new[] - { - new AbbreviationsForCulture("en-US", "Dth (E.C.)"), - new AbbreviationsForCulture("ru-RU", "Европейский декатерм"), - }), - new CulturesForEnumValue((int) EnergyUnit.DecathermImperial, - new[] - { - new AbbreviationsForCulture("en-US", "Dth (imp.)"), - new AbbreviationsForCulture("ru-RU", "Английский декатерм"), - }), - new CulturesForEnumValue((int) EnergyUnit.DecathermUs, - new[] - { - new AbbreviationsForCulture("en-US", "Dth (U.S.)"), - new AbbreviationsForCulture("ru-RU", "Американский декатерм"), - }), - new CulturesForEnumValue((int) EnergyUnit.ElectronVolt, - new[] - { - new AbbreviationsForCulture("en-US", "eV"), - }), - new CulturesForEnumValue((int) EnergyUnit.Erg, - new[] - { - new AbbreviationsForCulture("en-US", "erg"), - }), - new CulturesForEnumValue((int) EnergyUnit.FootPound, - new[] - { - new AbbreviationsForCulture("en-US", "ft·lb"), - }), - new CulturesForEnumValue((int) EnergyUnit.GigabritishThermalUnit, - new[] - { - new AbbreviationsForCulture("en-US", "GBTU"), - }), - new CulturesForEnumValue((int) EnergyUnit.GigawattHour, - new[] - { - new AbbreviationsForCulture("en-US", "GWh"), - new AbbreviationsForCulture("en-US", "GВт/ч"), - }), - new CulturesForEnumValue((int) EnergyUnit.Joule, - new[] - { - new AbbreviationsForCulture("en-US", "J"), - }), - new CulturesForEnumValue((int) EnergyUnit.KilobritishThermalUnit, - new[] - { - new AbbreviationsForCulture("en-US", "kBTU"), - }), - new CulturesForEnumValue((int) EnergyUnit.Kilocalorie, - new[] - { - new AbbreviationsForCulture("en-US", "kcal"), - }), - new CulturesForEnumValue((int) EnergyUnit.Kilojoule, - new[] - { - new AbbreviationsForCulture("en-US", "kJ"), - }), - new CulturesForEnumValue((int) EnergyUnit.KilowattHour, - new[] - { - new AbbreviationsForCulture("en-US", "kWh"), - new AbbreviationsForCulture("en-US", "kВт/ч"), - }), - new CulturesForEnumValue((int) EnergyUnit.MegabritishThermalUnit, - new[] - { - new AbbreviationsForCulture("en-US", "MBTU"), - }), - new CulturesForEnumValue((int) EnergyUnit.Megajoule, - new[] - { - new AbbreviationsForCulture("en-US", "MJ"), - }), - new CulturesForEnumValue((int) EnergyUnit.MegawattHour, - new[] - { - new AbbreviationsForCulture("en-US", "MWh"), - new AbbreviationsForCulture("en-US", "MВт/ч"), - }), - new CulturesForEnumValue((int) EnergyUnit.ThermEc, - new[] - { - new AbbreviationsForCulture("en-US", "th (E.C.)"), - new AbbreviationsForCulture("ru-RU", "Европейский терм"), - }), - new CulturesForEnumValue((int) EnergyUnit.ThermImperial, - new[] - { - new AbbreviationsForCulture("en-US", "th (imp.)"), - new AbbreviationsForCulture("ru-RU", "Английский терм"), - }), - new CulturesForEnumValue((int) EnergyUnit.ThermUs, - new[] - { - new AbbreviationsForCulture("en-US", "th (U.S.)"), - new AbbreviationsForCulture("ru-RU", "Американский терм"), - }), - new CulturesForEnumValue((int) EnergyUnit.WattHour, - new[] - { - new AbbreviationsForCulture("en-US", "Wh"), - new AbbreviationsForCulture("en-US", "Вт/ч"), - }), - }), - new UnitLocalization(typeof (EntropyUnit), - new[] - { - new CulturesForEnumValue((int) EntropyUnit.CaloriePerKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "cal/K"), - }), - new CulturesForEnumValue((int) EntropyUnit.JoulePerDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "J/C"), - }), - new CulturesForEnumValue((int) EntropyUnit.JoulePerKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "J/K"), - }), - new CulturesForEnumValue((int) EntropyUnit.KilocaloriePerKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "kcal/K"), - }), - new CulturesForEnumValue((int) EntropyUnit.KilojoulePerDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/C"), - }), - new CulturesForEnumValue((int) EntropyUnit.KilojoulePerKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/K"), - }), - new CulturesForEnumValue((int) EntropyUnit.MegajoulePerKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/K"), - }), - }), - new UnitLocalization(typeof (FlowUnit), - new[] - { - new CulturesForEnumValue((int) FlowUnit.CentilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "cLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicDecimeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "dm³/min"), - new AbbreviationsForCulture("ru-RU", "дм³/мин"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicFootPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/h", "cf/hr"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicFootPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/min"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicFootPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/s"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicMeterPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "m³/h"), - new AbbreviationsForCulture("ru-RU", "м³/ч"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicMeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "m³/min"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicMeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m³/s"), - new AbbreviationsForCulture("ru-RU", "м³/с"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicYardPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/h"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicYardPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/min"), - }), - new CulturesForEnumValue((int) FlowUnit.CubicYardPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/s"), - }), - new CulturesForEnumValue((int) FlowUnit.DecilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "dLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.KilolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.LitersPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "LPH"), - new AbbreviationsForCulture("ru-RU", "л/ч"), - }), - new CulturesForEnumValue((int) FlowUnit.LitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "LPM"), - }), - new CulturesForEnumValue((int) FlowUnit.LitersPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "LPS"), - }), - new CulturesForEnumValue((int) FlowUnit.MicrolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "µLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.MillilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "mLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.MillionUsGallonsPerDay, - new[] - { - new AbbreviationsForCulture("en-US", "MGD"), - }), - new CulturesForEnumValue((int) FlowUnit.NanolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "nLPM"), - }), - new CulturesForEnumValue((int) FlowUnit.OilBarrelsPerDay, - new[] - { - new AbbreviationsForCulture("en-US", "bbl/d", "BOPD"), - }), - new CulturesForEnumValue((int) FlowUnit.UsGallonsPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/h"), - }), - new CulturesForEnumValue((int) FlowUnit.UsGallonsPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/min", "GPM"), - }), - new CulturesForEnumValue((int) FlowUnit.UsGallonsPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/s"), - }), - }), - new UnitLocalization(typeof (ForceUnit), - new[] - { - new CulturesForEnumValue((int) ForceUnit.Decanewton, - new[] - { - new AbbreviationsForCulture("en-US", "daN"), - new AbbreviationsForCulture("ru-RU", "даН"), - }), - new CulturesForEnumValue((int) ForceUnit.Dyn, - new[] - { - new AbbreviationsForCulture("en-US", "dyn"), - new AbbreviationsForCulture("ru-RU", "дин"), - }), - new CulturesForEnumValue((int) ForceUnit.KilogramForce, - new[] - { - new AbbreviationsForCulture("en-US", "kgf"), - new AbbreviationsForCulture("ru-RU", "кгс"), - }), - new CulturesForEnumValue((int) ForceUnit.Kilonewton, - new[] - { - new AbbreviationsForCulture("en-US", "kN"), - new AbbreviationsForCulture("ru-RU", "кН"), - }), - new CulturesForEnumValue((int) ForceUnit.KiloPond, - new[] - { - new AbbreviationsForCulture("en-US", "kp"), - new AbbreviationsForCulture("ru-RU", "кгс"), - }), - new CulturesForEnumValue((int) ForceUnit.Meganewton, - new[] - { - new AbbreviationsForCulture("en-US", "MN"), - new AbbreviationsForCulture("ru-RU", "МН"), - }), - new CulturesForEnumValue((int) ForceUnit.Micronewton, - new[] - { - new AbbreviationsForCulture("en-US", "µN"), - new AbbreviationsForCulture("ru-RU", "мкН"), - }), - new CulturesForEnumValue((int) ForceUnit.Millinewton, - new[] - { - new AbbreviationsForCulture("en-US", "mN"), - new AbbreviationsForCulture("ru-RU", "мН"), - }), - new CulturesForEnumValue((int) ForceUnit.Newton, - new[] - { - new AbbreviationsForCulture("en-US", "N"), - new AbbreviationsForCulture("ru-RU", "Н"), - }), - new CulturesForEnumValue((int) ForceUnit.OunceForce, - new[] - { - new AbbreviationsForCulture("en-US", "ozf"), - }), - new CulturesForEnumValue((int) ForceUnit.Poundal, - new[] - { - new AbbreviationsForCulture("en-US", "pdl"), - new AbbreviationsForCulture("ru-RU", "паундаль"), - }), - new CulturesForEnumValue((int) ForceUnit.PoundForce, - new[] - { - new AbbreviationsForCulture("en-US", "lbf"), - new AbbreviationsForCulture("ru-RU", "фунт-сила"), - }), - new CulturesForEnumValue((int) ForceUnit.TonneForce, - new[] - { - new AbbreviationsForCulture("en-US", "Ton"), - new AbbreviationsForCulture("ru-RU", "тс"), - }), - }), - new UnitLocalization(typeof (ForceChangeRateUnit), - new[] - { - new CulturesForEnumValue((int) ForceChangeRateUnit.CentinewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "cN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.DecanewtonPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "daN/min"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.DecanewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "daN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.DecinewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "dN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.KilonewtonPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kN/min"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.KilonewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.MicronewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.MillinewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.NanonewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "nN/s"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.NewtonPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "N/min"), - }), - new CulturesForEnumValue((int) ForceChangeRateUnit.NewtonPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "N/s"), - }), - }), - new UnitLocalization(typeof (ForcePerLengthUnit), - new[] - { - new CulturesForEnumValue((int) ForcePerLengthUnit.CentinewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "cN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.DecinewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "dN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.KilogramForcePerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/m"), - new AbbreviationsForCulture("ru-RU", "кгс/м"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.KilonewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.MeganewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.MicronewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "µN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.MillinewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.NanonewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "nN/m"), - }), - new CulturesForEnumValue((int) ForcePerLengthUnit.NewtonPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/m"), - }), - }), - new UnitLocalization(typeof (FrequencyUnit), - new[] - { - new CulturesForEnumValue((int) FrequencyUnit.CyclePerHour, - new[] - { - new AbbreviationsForCulture("en-US", "cph"), - }), - new CulturesForEnumValue((int) FrequencyUnit.CyclePerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "cpm"), - }), - new CulturesForEnumValue((int) FrequencyUnit.Gigahertz, - new[] - { - new AbbreviationsForCulture("en-US", "GHz"), - }), - new CulturesForEnumValue((int) FrequencyUnit.Hertz, - new[] - { - new AbbreviationsForCulture("en-US", "Hz"), - }), - new CulturesForEnumValue((int) FrequencyUnit.Kilohertz, - new[] - { - new AbbreviationsForCulture("en-US", "kHz"), - }), - new CulturesForEnumValue((int) FrequencyUnit.Megahertz, - new[] - { - new AbbreviationsForCulture("en-US", "MHz"), - }), - new CulturesForEnumValue((int) FrequencyUnit.RadianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "rad/s"), - }), - new CulturesForEnumValue((int) FrequencyUnit.Terahertz, - new[] - { - new AbbreviationsForCulture("en-US", "THz"), - }), - }), - new UnitLocalization(typeof (HeatFluxUnit), - new[] - { - new CulturesForEnumValue((int) HeatFluxUnit.BtuPerHourSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "BTU/h·ft²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.BtuPerMinuteSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "BTU/min·ft²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.BtuPerSecondSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "BTU/s·ft²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.BtuPerSecondSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "BTU/s·in²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.CaloriePerSecondSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "cal/s·cm²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.CentiwattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "cW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.DeciwattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "dW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.KilocaloriePerHourSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kcal/h·m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kcal/s·cm²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.KilowattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.MicrowattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "µW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.MilliwattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.NanowattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "nW/m²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.PoundForcePerFootSecond, - new[] - { - new AbbreviationsForCulture("en-US", "lbf/(ft·s)"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.PoundPerSecondCubed, - new[] - { - new AbbreviationsForCulture("en-US", "lb/s³", "lbm/s³"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.WattPerSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "W/ft²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.WattPerSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "W/in²"), - }), - new CulturesForEnumValue((int) HeatFluxUnit.WattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "W/m²"), - }), - }), - new UnitLocalization(typeof (HeatTransferCoefficientUnit), - new[] - { - new CulturesForEnumValue((int) HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "W/m²·°C"), - }), - new CulturesForEnumValue((int) HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "W/m²·K"), - }), - }), - new UnitLocalization(typeof (IlluminanceUnit), - new[] - { - new CulturesForEnumValue((int) IlluminanceUnit.Kilolux, - new[] - { - new AbbreviationsForCulture("en-US", "klx"), - }), - new CulturesForEnumValue((int) IlluminanceUnit.Lux, - new[] - { - new AbbreviationsForCulture("en-US", "lx"), - }), - new CulturesForEnumValue((int) IlluminanceUnit.Megalux, - new[] - { - new AbbreviationsForCulture("en-US", "Mlx"), - }), - new CulturesForEnumValue((int) IlluminanceUnit.Millilux, - new[] - { - new AbbreviationsForCulture("en-US", "mlx"), - }), - }), - new UnitLocalization(typeof (InformationUnit), - new[] - { - new CulturesForEnumValue((int) InformationUnit.Bit, - new[] - { - new AbbreviationsForCulture("en-US", "b"), - }), - new CulturesForEnumValue((int) InformationUnit.Byte, - new[] - { - new AbbreviationsForCulture("en-US", "B"), - }), - new CulturesForEnumValue((int) InformationUnit.Exabit, - new[] - { - new AbbreviationsForCulture("en-US", "Eb"), - }), - new CulturesForEnumValue((int) InformationUnit.Exabyte, - new[] - { - new AbbreviationsForCulture("en-US", "EB"), - }), - new CulturesForEnumValue((int) InformationUnit.Exbibit, - new[] - { - new AbbreviationsForCulture("en-US", "Eib"), - }), - new CulturesForEnumValue((int) InformationUnit.Exbibyte, - new[] - { - new AbbreviationsForCulture("en-US", "EiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Gibibit, - new[] - { - new AbbreviationsForCulture("en-US", "Gib"), - }), - new CulturesForEnumValue((int) InformationUnit.Gibibyte, - new[] - { - new AbbreviationsForCulture("en-US", "GiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Gigabit, - new[] - { - new AbbreviationsForCulture("en-US", "Gb"), - }), - new CulturesForEnumValue((int) InformationUnit.Gigabyte, - new[] - { - new AbbreviationsForCulture("en-US", "GB"), - }), - new CulturesForEnumValue((int) InformationUnit.Kibibit, - new[] - { - new AbbreviationsForCulture("en-US", "Kib"), - }), - new CulturesForEnumValue((int) InformationUnit.Kibibyte, - new[] - { - new AbbreviationsForCulture("en-US", "KiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Kilobit, - new[] - { - new AbbreviationsForCulture("en-US", "kb"), - }), - new CulturesForEnumValue((int) InformationUnit.Kilobyte, - new[] - { - new AbbreviationsForCulture("en-US", "kB"), - }), - new CulturesForEnumValue((int) InformationUnit.Mebibit, - new[] - { - new AbbreviationsForCulture("en-US", "Mib"), - }), - new CulturesForEnumValue((int) InformationUnit.Mebibyte, - new[] - { - new AbbreviationsForCulture("en-US", "MiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Megabit, - new[] - { - new AbbreviationsForCulture("en-US", "Mb"), - }), - new CulturesForEnumValue((int) InformationUnit.Megabyte, - new[] - { - new AbbreviationsForCulture("en-US", "MB"), - }), - new CulturesForEnumValue((int) InformationUnit.Pebibit, - new[] - { - new AbbreviationsForCulture("en-US", "Pib"), - }), - new CulturesForEnumValue((int) InformationUnit.Pebibyte, - new[] - { - new AbbreviationsForCulture("en-US", "PiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Petabit, - new[] - { - new AbbreviationsForCulture("en-US", "Pb"), - }), - new CulturesForEnumValue((int) InformationUnit.Petabyte, - new[] - { - new AbbreviationsForCulture("en-US", "PB"), - }), - new CulturesForEnumValue((int) InformationUnit.Tebibit, - new[] - { - new AbbreviationsForCulture("en-US", "Tib"), - }), - new CulturesForEnumValue((int) InformationUnit.Tebibyte, - new[] - { - new AbbreviationsForCulture("en-US", "TiB"), - }), - new CulturesForEnumValue((int) InformationUnit.Terabit, - new[] - { - new AbbreviationsForCulture("en-US", "Tb"), - }), - new CulturesForEnumValue((int) InformationUnit.Terabyte, - new[] - { - new AbbreviationsForCulture("en-US", "TB"), - }), - }), - new UnitLocalization(typeof (IrradianceUnit), - new[] - { - new CulturesForEnumValue((int) IrradianceUnit.KilowattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kW/m²"), - }), - new CulturesForEnumValue((int) IrradianceUnit.WattPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "W/m²"), - }), - }), - new UnitLocalization(typeof (IrradiationUnit), - new[] - { - new CulturesForEnumValue((int) IrradiationUnit.JoulePerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "J/m²"), - }), - new CulturesForEnumValue((int) IrradiationUnit.KilowattHourPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kWh/m²"), - }), - new CulturesForEnumValue((int) IrradiationUnit.WattHourPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "Wh/m²"), - }), - }), - new UnitLocalization(typeof (KinematicViscosityUnit), - new[] - { - new CulturesForEnumValue((int) KinematicViscosityUnit.Centistokes, - new[] - { - new AbbreviationsForCulture("en-US", "cSt"), - new AbbreviationsForCulture("ru-RU", "сСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Decistokes, - new[] - { - new AbbreviationsForCulture("en-US", "dSt"), - new AbbreviationsForCulture("ru-RU", "дСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Kilostokes, - new[] - { - new AbbreviationsForCulture("en-US", "kSt"), - new AbbreviationsForCulture("ru-RU", "кСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Microstokes, - new[] - { - new AbbreviationsForCulture("en-US", "µSt"), - new AbbreviationsForCulture("ru-RU", "мкСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Millistokes, - new[] - { - new AbbreviationsForCulture("en-US", "mSt"), - new AbbreviationsForCulture("ru-RU", "мСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Nanostokes, - new[] - { - new AbbreviationsForCulture("en-US", "nSt"), - new AbbreviationsForCulture("ru-RU", "нСт"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.SquareMeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m²/s"), - new AbbreviationsForCulture("ru-RU", "м²/с"), - }), - new CulturesForEnumValue((int) KinematicViscosityUnit.Stokes, - new[] - { - new AbbreviationsForCulture("en-US", "St"), - new AbbreviationsForCulture("ru-RU", "Ст"), - }), - }), - new UnitLocalization(typeof (LapseRateUnit), - new[] - { - new CulturesForEnumValue((int) LapseRateUnit.DegreeCelsiusPerKilometer, - new[] - { - new AbbreviationsForCulture("en-US", "∆°C/km"), - }), - }), - new UnitLocalization(typeof (LengthUnit), - new[] - { - new CulturesForEnumValue((int) LengthUnit.Centimeter, - new[] - { - new AbbreviationsForCulture("en-US", "cm"), - new AbbreviationsForCulture("ru-RU", "см"), - }), - new CulturesForEnumValue((int) LengthUnit.Decimeter, - new[] - { - new AbbreviationsForCulture("en-US", "dm"), - new AbbreviationsForCulture("ru-RU", "дм"), - }), - new CulturesForEnumValue((int) LengthUnit.DtpPica, - new[] - { - new AbbreviationsForCulture("en-US", "pica"), - }), - new CulturesForEnumValue((int) LengthUnit.DtpPoint, - new[] - { - new AbbreviationsForCulture("en-US", "pt"), - }), - new CulturesForEnumValue((int) LengthUnit.Fathom, - new[] - { - new AbbreviationsForCulture("en-US", "fathom"), - }), - new CulturesForEnumValue((int) LengthUnit.Foot, - new[] - { - new AbbreviationsForCulture("en-US", "ft", "'"), - new AbbreviationsForCulture("ru-RU", "фут"), - }), - new CulturesForEnumValue((int) LengthUnit.Inch, - new[] - { - new AbbreviationsForCulture("en-US", "in", "\""), - new AbbreviationsForCulture("ru-RU", "дюйм"), - }), - new CulturesForEnumValue((int) LengthUnit.Kilometer, - new[] - { - new AbbreviationsForCulture("en-US", "km"), - new AbbreviationsForCulture("ru-RU", "км"), - }), - new CulturesForEnumValue((int) LengthUnit.Meter, - new[] - { - new AbbreviationsForCulture("en-US", "m"), - new AbbreviationsForCulture("ru-RU", "м"), - }), - new CulturesForEnumValue((int) LengthUnit.Microinch, - new[] - { - new AbbreviationsForCulture("en-US", "µin"), - new AbbreviationsForCulture("ru-RU", "микродюйм"), - }), - new CulturesForEnumValue((int) LengthUnit.Micrometer, - new[] - { - new AbbreviationsForCulture("en-US", "µm"), - new AbbreviationsForCulture("ru-RU", "мкм"), - }), - new CulturesForEnumValue((int) LengthUnit.Mil, - new[] - { - new AbbreviationsForCulture("en-US", "mil"), - new AbbreviationsForCulture("ru-RU", "мил"), - }), - new CulturesForEnumValue((int) LengthUnit.Mile, - new[] - { - new AbbreviationsForCulture("en-US", "mi"), - new AbbreviationsForCulture("ru-RU", "миля"), - }), - new CulturesForEnumValue((int) LengthUnit.Millimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mm"), - new AbbreviationsForCulture("ru-RU", "мм"), - }), - new CulturesForEnumValue((int) LengthUnit.Nanometer, - new[] - { - new AbbreviationsForCulture("en-US", "nm"), - new AbbreviationsForCulture("ru-RU", "нм"), - }), - new CulturesForEnumValue((int) LengthUnit.NauticalMile, - new[] - { - new AbbreviationsForCulture("en-US", "NM"), - new AbbreviationsForCulture("ru-RU", "мил"), - }), - new CulturesForEnumValue((int) LengthUnit.PrinterPica, - new[] - { - new AbbreviationsForCulture("en-US", "pica"), - }), - new CulturesForEnumValue((int) LengthUnit.PrinterPoint, - new[] - { - new AbbreviationsForCulture("en-US", "pt"), - }), - new CulturesForEnumValue((int) LengthUnit.Shackle, - new[] - { - new AbbreviationsForCulture("en-US", "shackle"), - }), - new CulturesForEnumValue((int) LengthUnit.Twip, - new[] - { - new AbbreviationsForCulture("en-US", "twip"), - }), - new CulturesForEnumValue((int) LengthUnit.UsSurveyFoot, - new[] - { - new AbbreviationsForCulture("en-US", "ftUS"), - }), - new CulturesForEnumValue((int) LengthUnit.Yard, - new[] - { - new AbbreviationsForCulture("en-US", "yd"), - new AbbreviationsForCulture("ru-RU", "ярд"), - }), - }), - new UnitLocalization(typeof (LevelUnit), - new[] - { - new CulturesForEnumValue((int) LevelUnit.Decibel, - new[] - { - new AbbreviationsForCulture("en-US", "dB"), - }), - new CulturesForEnumValue((int) LevelUnit.Neper, - new[] - { - new AbbreviationsForCulture("en-US", "Np"), - }), - }), - new UnitLocalization(typeof (LinearDensityUnit), - new[] - { - new CulturesForEnumValue((int) LinearDensityUnit.GramPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "g/m"), - }), - new CulturesForEnumValue((int) LinearDensityUnit.KilogramPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg/m"), - }), - new CulturesForEnumValue((int) LinearDensityUnit.PoundPerFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lb/ft"), - }), - }), - new UnitLocalization(typeof (LuminousFluxUnit), - new[] - { - new CulturesForEnumValue((int) LuminousFluxUnit.Lumen, - new[] - { - new AbbreviationsForCulture("en-US", "lm"), - }), - }), - new UnitLocalization(typeof (LuminousIntensityUnit), - new[] - { - new CulturesForEnumValue((int) LuminousIntensityUnit.Candela, - new[] - { - new AbbreviationsForCulture("en-US", "cd"), - }), - }), - new UnitLocalization(typeof (MagneticFieldUnit), - new[] - { - new CulturesForEnumValue((int) MagneticFieldUnit.Microtesla, - new[] - { - new AbbreviationsForCulture("en-US", "µT"), - }), - new CulturesForEnumValue((int) MagneticFieldUnit.Millitesla, - new[] - { - new AbbreviationsForCulture("en-US", "mT"), - }), - new CulturesForEnumValue((int) MagneticFieldUnit.Nanotesla, - new[] - { - new AbbreviationsForCulture("en-US", "nT"), - }), - new CulturesForEnumValue((int) MagneticFieldUnit.Tesla, - new[] - { - new AbbreviationsForCulture("en-US", "T"), - }), - }), - new UnitLocalization(typeof (MagneticFluxUnit), - new[] - { - new CulturesForEnumValue((int) MagneticFluxUnit.Weber, - new[] - { - new AbbreviationsForCulture("en-US", "Wb"), - }), - }), - new UnitLocalization(typeof (MagnetizationUnit), - new[] - { - new CulturesForEnumValue((int) MagnetizationUnit.AmperePerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "A/m"), - }), - }), - new UnitLocalization(typeof (MassUnit), - new[] - { - new CulturesForEnumValue((int) MassUnit.Centigram, - new[] - { - new AbbreviationsForCulture("en-US", "cg"), - new AbbreviationsForCulture("ru-RU", "сг"), - }), - new CulturesForEnumValue((int) MassUnit.Decagram, - new[] - { - new AbbreviationsForCulture("en-US", "dag"), - new AbbreviationsForCulture("ru-RU", "даг"), - }), - new CulturesForEnumValue((int) MassUnit.Decigram, - new[] - { - new AbbreviationsForCulture("en-US", "dg"), - new AbbreviationsForCulture("ru-RU", "дг"), - }), - new CulturesForEnumValue((int) MassUnit.Gram, - new[] - { - new AbbreviationsForCulture("en-US", "g"), - new AbbreviationsForCulture("ru-RU", "г"), - }), - new CulturesForEnumValue((int) MassUnit.Hectogram, - new[] - { - new AbbreviationsForCulture("en-US", "hg"), - new AbbreviationsForCulture("ru-RU", "гг"), - }), - new CulturesForEnumValue((int) MassUnit.Kilogram, - new[] - { - new AbbreviationsForCulture("en-US", "kg"), - new AbbreviationsForCulture("ru-RU", "кг"), - }), - new CulturesForEnumValue((int) MassUnit.Kilopound, - new[] - { - new AbbreviationsForCulture("en-US", "klb"), - new AbbreviationsForCulture("ru-RU", "kфунт"), - }), - new CulturesForEnumValue((int) MassUnit.Kilotonne, - new[] - { - new AbbreviationsForCulture("en-US", "kt"), - new AbbreviationsForCulture("ru-RU", "кт"), - }), - new CulturesForEnumValue((int) MassUnit.LongHundredweight, - new[] - { - new AbbreviationsForCulture("en-US", "cwt"), - }), - new CulturesForEnumValue((int) MassUnit.LongTon, - new[] - { - new AbbreviationsForCulture("en-US", "long tn"), - new AbbreviationsForCulture("ru-RU", "тонна большая"), - }), - new CulturesForEnumValue((int) MassUnit.Megapound, - new[] - { - new AbbreviationsForCulture("en-US", "Mlb"), - new AbbreviationsForCulture("ru-RU", "Mфунт"), - }), - new CulturesForEnumValue((int) MassUnit.Megatonne, - new[] - { - new AbbreviationsForCulture("en-US", "Mt"), - new AbbreviationsForCulture("ru-RU", "Мт"), - }), - new CulturesForEnumValue((int) MassUnit.Microgram, - new[] - { - new AbbreviationsForCulture("en-US", "µg"), - new AbbreviationsForCulture("ru-RU", "мкг"), - }), - new CulturesForEnumValue((int) MassUnit.Milligram, - new[] - { - new AbbreviationsForCulture("en-US", "mg"), - new AbbreviationsForCulture("ru-RU", "мг"), - }), - new CulturesForEnumValue((int) MassUnit.Nanogram, - new[] - { - new AbbreviationsForCulture("en-US", "ng"), - new AbbreviationsForCulture("ru-RU", "нг"), - }), - new CulturesForEnumValue((int) MassUnit.Ounce, - new[] - { - new AbbreviationsForCulture("en-US", "oz"), - }), - new CulturesForEnumValue((int) MassUnit.Pound, - new[] - { - new AbbreviationsForCulture("en-US", "lb", "lbs", "lbm"), - new AbbreviationsForCulture("ru-RU", "фунт"), - }), - new CulturesForEnumValue((int) MassUnit.ShortHundredweight, - new[] - { - new AbbreviationsForCulture("en-US", "cwt"), - }), - new CulturesForEnumValue((int) MassUnit.ShortTon, - new[] - { - new AbbreviationsForCulture("en-US", "short tn"), - new AbbreviationsForCulture("ru-RU", "тонна малая"), - }), - new CulturesForEnumValue((int) MassUnit.Slug, - new[] - { - new AbbreviationsForCulture("en-US", "slug"), - }), - new CulturesForEnumValue((int) MassUnit.Stone, - new[] - { - new AbbreviationsForCulture("en-US", "st"), - }), - new CulturesForEnumValue((int) MassUnit.Tonne, - new[] - { - new AbbreviationsForCulture("en-US", "t"), - new AbbreviationsForCulture("ru-RU", "т"), - }), - }), - new UnitLocalization(typeof (MassFlowUnit), - new[] - { - new CulturesForEnumValue((int) MassFlowUnit.CentigramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "cg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.DecagramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "dag/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.DecigramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "dg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.GramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "g/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.HectogramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "hg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.KilogramPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "kg/h"), - new AbbreviationsForCulture("ru-RU", "кг/ч"), - }), - new CulturesForEnumValue((int) MassFlowUnit.KilogramPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kg/min"), - new AbbreviationsForCulture("ru-RU", "кг/мин"), - }), - new CulturesForEnumValue((int) MassFlowUnit.KilogramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.MegapoundPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "Mlb/h"), - }), - new CulturesForEnumValue((int) MassFlowUnit.MegapoundPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "Mlb/min"), - }), - new CulturesForEnumValue((int) MassFlowUnit.MicrogramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.MilligramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mg/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.NanogramPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "ng/S"), - }), - new CulturesForEnumValue((int) MassFlowUnit.PoundPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "lb/h"), - }), - new CulturesForEnumValue((int) MassFlowUnit.PoundPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "lb/min"), - }), - new CulturesForEnumValue((int) MassFlowUnit.ShortTonPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "short tn/h"), - }), - new CulturesForEnumValue((int) MassFlowUnit.TonnePerDay, - new[] - { - new AbbreviationsForCulture("en-US", "t/d"), - }), - new CulturesForEnumValue((int) MassFlowUnit.TonnePerHour, - new[] - { - new AbbreviationsForCulture("en-US", "t/h"), - }), - }), - new UnitLocalization(typeof (MassFluxUnit), - new[] - { - new CulturesForEnumValue((int) MassFluxUnit.GramPerSecondPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "g·s⁻¹·m⁻²"), - }), - new CulturesForEnumValue((int) MassFluxUnit.KilogramPerSecondPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg·s⁻¹·m⁻²"), - }), - }), - new UnitLocalization(typeof (MassMomentOfInertiaUnit), - new[] - { - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.GramSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "g·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.GramSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "g·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.GramSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "g·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.GramSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "g·mm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilogramSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilogramSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilogramSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilogramSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kg·mm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilotonneSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kt·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilotonneSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kt·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilotonneSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kt·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.KilotonneSquareMilimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kt·mm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MegatonneSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "Mt·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MegatonneSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "Mt·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MegatonneSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "Mt·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MegatonneSquareMilimeter, - new[] - { - new AbbreviationsForCulture("en-US", "Mt·mm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MilligramSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mg·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MilligramSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mg·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MilligramSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mg·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.MilligramSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mg·mm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.PoundSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lb·ft²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.PoundSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "lb·in²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.SlugSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "slug·ft²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.SlugSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "slug·in²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.TonneSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "t·cm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.TonneSquareDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "t·dm²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.TonneSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "t·m²"), - }), - new CulturesForEnumValue((int) MassMomentOfInertiaUnit.TonneSquareMilimeter, - new[] - { - new AbbreviationsForCulture("en-US", "t·mm²"), - }), - }), - new UnitLocalization(typeof (MolarEnergyUnit), - new[] - { - new CulturesForEnumValue((int) MolarEnergyUnit.JoulePerMole, - new[] - { - new AbbreviationsForCulture("en-US", "J/mol"), - }), - new CulturesForEnumValue((int) MolarEnergyUnit.KilojoulePerMole, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/mol"), - }), - new CulturesForEnumValue((int) MolarEnergyUnit.MegajoulePerMole, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/mol"), - }), - }), - new UnitLocalization(typeof (MolarEntropyUnit), - new[] - { - new CulturesForEnumValue((int) MolarEntropyUnit.JoulePerMoleKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "J/(mol*K)"), - }), - new CulturesForEnumValue((int) MolarEntropyUnit.KilojoulePerMoleKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/(mol*K)"), - }), - new CulturesForEnumValue((int) MolarEntropyUnit.MegajoulePerMoleKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/(mol*K)"), - }), - }), - new UnitLocalization(typeof (MolarityUnit), - new[] - { - new CulturesForEnumValue((int) MolarityUnit.CentimolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "cmol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.DecimolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "dmol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.MicromolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "µmol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.MillimolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "mmol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.MolesPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mol/m³"), - }), - new CulturesForEnumValue((int) MolarityUnit.MolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "mol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.NanomolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "nmol/L"), - }), - new CulturesForEnumValue((int) MolarityUnit.PicomolesPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "pmol/L"), - }), - }), - new UnitLocalization(typeof (MolarMassUnit), - new[] - { - new CulturesForEnumValue((int) MolarMassUnit.CentigramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "cg/mol"), - new AbbreviationsForCulture("ru-RU", "сг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.DecagramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "dag/mol"), - new AbbreviationsForCulture("ru-RU", "даг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.DecigramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "dg/mol"), - new AbbreviationsForCulture("ru-RU", "дг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.GramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "g/mol"), - new AbbreviationsForCulture("ru-RU", "г/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.HectogramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "hg/mol"), - new AbbreviationsForCulture("ru-RU", "гг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.KilogramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "kg/mol"), - new AbbreviationsForCulture("ru-RU", "кг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.KilopoundPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "klb/mol"), - new AbbreviationsForCulture("ru-RU", "kфунт/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.MegapoundPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "Mlb/mol"), - new AbbreviationsForCulture("ru-RU", "Mфунт/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.MicrogramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "µg/mol"), - new AbbreviationsForCulture("ru-RU", "мкг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.MilligramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "mg/mol"), - new AbbreviationsForCulture("ru-RU", "мг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.NanogramPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "ng/mol"), - new AbbreviationsForCulture("ru-RU", "нг/моль"), - }), - new CulturesForEnumValue((int) MolarMassUnit.PoundPerMole, - new[] - { - new AbbreviationsForCulture("en-US", "lb/mol"), - new AbbreviationsForCulture("ru-RU", "фунт/моль"), - }), - }), - new UnitLocalization(typeof (PermeabilityUnit), - new[] - { - new CulturesForEnumValue((int) PermeabilityUnit.HenryPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "H/m"), - }), - }), - new UnitLocalization(typeof (PermittivityUnit), - new[] - { - new CulturesForEnumValue((int) PermittivityUnit.FaradPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "F/m"), - }), - }), - new UnitLocalization(typeof (PowerUnit), - new[] - { - new CulturesForEnumValue((int) PowerUnit.BoilerHorsepower, - new[] - { - new AbbreviationsForCulture("en-US", "hp(S)"), - }), - new CulturesForEnumValue((int) PowerUnit.BritishThermalUnitPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "Btu/hr"), - }), - new CulturesForEnumValue((int) PowerUnit.Decawatt, - new[] - { - new AbbreviationsForCulture("en-US", "daW"), - }), - new CulturesForEnumValue((int) PowerUnit.Deciwatt, - new[] - { - new AbbreviationsForCulture("en-US", "dW"), - }), - new CulturesForEnumValue((int) PowerUnit.ElectricalHorsepower, - new[] - { - new AbbreviationsForCulture("en-US", "hp(E)"), - }), - new CulturesForEnumValue((int) PowerUnit.Femtowatt, - new[] - { - new AbbreviationsForCulture("en-US", "fW"), - }), - new CulturesForEnumValue((int) PowerUnit.Gigawatt, - new[] - { - new AbbreviationsForCulture("en-US", "GW"), - }), - new CulturesForEnumValue((int) PowerUnit.HydraulicHorsepower, - new[] - { - new AbbreviationsForCulture("en-US", "hp(H)"), - }), - new CulturesForEnumValue((int) PowerUnit.KilobritishThermalUnitPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "kBtu/hr"), - }), - new CulturesForEnumValue((int) PowerUnit.Kilowatt, - new[] - { - new AbbreviationsForCulture("en-US", "kW"), - }), - new CulturesForEnumValue((int) PowerUnit.MechanicalHorsepower, - new[] - { - new AbbreviationsForCulture("en-US", "hp(I)"), - }), - new CulturesForEnumValue((int) PowerUnit.Megawatt, - new[] - { - new AbbreviationsForCulture("en-US", "MW"), - }), - new CulturesForEnumValue((int) PowerUnit.MetricHorsepower, - new[] - { - new AbbreviationsForCulture("en-US", "hp(M)"), - }), - new CulturesForEnumValue((int) PowerUnit.Microwatt, - new[] - { - new AbbreviationsForCulture("en-US", "µW"), - }), - new CulturesForEnumValue((int) PowerUnit.Milliwatt, - new[] - { - new AbbreviationsForCulture("en-US", "mW"), - }), - new CulturesForEnumValue((int) PowerUnit.Nanowatt, - new[] - { - new AbbreviationsForCulture("en-US", "nW"), - }), - new CulturesForEnumValue((int) PowerUnit.Petawatt, - new[] - { - new AbbreviationsForCulture("en-US", "PW"), - }), - new CulturesForEnumValue((int) PowerUnit.Picowatt, - new[] - { - new AbbreviationsForCulture("en-US", "pW"), - }), - new CulturesForEnumValue((int) PowerUnit.Terawatt, - new[] - { - new AbbreviationsForCulture("en-US", "TW"), - }), - new CulturesForEnumValue((int) PowerUnit.Watt, - new[] - { - new AbbreviationsForCulture("en-US", "W"), - }), - }), - new UnitLocalization(typeof (PowerDensityUnit), - new[] - { - new CulturesForEnumValue((int) PowerDensityUnit.DecawattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "daW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DecawattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "daW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DecawattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "daW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DecawattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "daW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DeciwattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "dW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DeciwattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "dW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DeciwattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "dW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.DeciwattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "dW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.GigawattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "GW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.GigawattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "GW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.GigawattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "GW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.GigawattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "GW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.KilowattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.KilowattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "kW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.KilowattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.KilowattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "kW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MegawattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "MW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MegawattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "MW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MegawattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MegawattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "MW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MicrowattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "µW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MicrowattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "µW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MicrowattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "µW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MicrowattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "µW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MilliwattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "mW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MilliwattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "mW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MilliwattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "mW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.MilliwattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "mW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.NanowattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "nW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.NanowattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "nW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.NanowattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "nW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.NanowattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "nW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.PicowattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "pW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.PicowattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "pW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.PicowattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "pW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.PicowattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "pW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.TerawattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "TW/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.TerawattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "TW/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.TerawattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "TW/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.TerawattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "TW/l"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.WattPerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "W/ft³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.WattPerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "W/in³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.WattPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "W/m³"), - }), - new CulturesForEnumValue((int) PowerDensityUnit.WattPerLiter, - new[] - { - new AbbreviationsForCulture("en-US", "W/l"), - }), - }), - new UnitLocalization(typeof (PowerRatioUnit), - new[] - { - new CulturesForEnumValue((int) PowerRatioUnit.DecibelMilliwatt, - new[] - { - new AbbreviationsForCulture("en-US", "dBmW", "dBm"), - }), - new CulturesForEnumValue((int) PowerRatioUnit.DecibelWatt, - new[] - { - new AbbreviationsForCulture("en-US", "dBW"), - }), - }), - new UnitLocalization(typeof (PressureUnit), - new[] - { - new CulturesForEnumValue((int) PressureUnit.Atmosphere, - new[] - { - new AbbreviationsForCulture("en-US", "atm"), - new AbbreviationsForCulture("ru-RU", "атм"), - }), - new CulturesForEnumValue((int) PressureUnit.Bar, - new[] - { - new AbbreviationsForCulture("en-US", "bar"), - new AbbreviationsForCulture("ru-RU", "бар"), - }), - new CulturesForEnumValue((int) PressureUnit.Centibar, - new[] - { - new AbbreviationsForCulture("en-US", "cbar"), - new AbbreviationsForCulture("ru-RU", "cбар"), - }), - new CulturesForEnumValue((int) PressureUnit.Decapascal, - new[] - { - new AbbreviationsForCulture("en-US", "daPa"), - new AbbreviationsForCulture("ru-RU", "даПа"), - }), - new CulturesForEnumValue((int) PressureUnit.Decibar, - new[] - { - new AbbreviationsForCulture("en-US", "dbar"), - new AbbreviationsForCulture("ru-RU", "dбар"), - }), - new CulturesForEnumValue((int) PressureUnit.DynePerSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "dyn/cm²"), - }), - new CulturesForEnumValue((int) PressureUnit.FootOfHead, - new[] - { - new AbbreviationsForCulture("en-US", "ft of head"), - }), - new CulturesForEnumValue((int) PressureUnit.Gigapascal, - new[] - { - new AbbreviationsForCulture("en-US", "GPa"), - new AbbreviationsForCulture("ru-RU", "ГПа"), - }), - new CulturesForEnumValue((int) PressureUnit.Hectopascal, - new[] - { - new AbbreviationsForCulture("en-US", "hPa"), - new AbbreviationsForCulture("ru-RU", "гПа"), - }), - new CulturesForEnumValue((int) PressureUnit.InchOfMercury, - new[] - { - new AbbreviationsForCulture("en-US", "inHg"), - }), - new CulturesForEnumValue((int) PressureUnit.Kilobar, - new[] - { - new AbbreviationsForCulture("en-US", "kbar"), - new AbbreviationsForCulture("ru-RU", "kбар"), - }), - new CulturesForEnumValue((int) PressureUnit.KilogramForcePerSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/cm²"), - new AbbreviationsForCulture("ru-RU", "кгс/см²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilogramForcePerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/m²"), - new AbbreviationsForCulture("ru-RU", "кгс/м²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilogramForcePerSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/mm²"), - new AbbreviationsForCulture("ru-RU", "кгс/мм²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilonewtonPerSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/cm²"), - new AbbreviationsForCulture("ru-RU", "кН/см²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilonewtonPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/m²"), - new AbbreviationsForCulture("ru-RU", "кН/м²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilonewtonPerSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/mm²"), - new AbbreviationsForCulture("ru-RU", "кН/мм²"), - }), - new CulturesForEnumValue((int) PressureUnit.Kilopascal, - new[] - { - new AbbreviationsForCulture("en-US", "kPa"), - new AbbreviationsForCulture("ru-RU", "кПа"), - }), - new CulturesForEnumValue((int) PressureUnit.KilopoundForcePerSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kipf/ft²"), - }), - new CulturesForEnumValue((int) PressureUnit.KilopoundForcePerSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "kipf/in²"), - }), - new CulturesForEnumValue((int) PressureUnit.Megabar, - new[] - { - new AbbreviationsForCulture("en-US", "Mbar"), - new AbbreviationsForCulture("ru-RU", "Mбар"), - }), - new CulturesForEnumValue((int) PressureUnit.MeganewtonPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN/m²"), - new AbbreviationsForCulture("ru-RU", "Мн/м²"), - }), - new CulturesForEnumValue((int) PressureUnit.Megapascal, - new[] - { - new AbbreviationsForCulture("en-US", "MPa"), - new AbbreviationsForCulture("ru-RU", "МПа"), - }), - new CulturesForEnumValue((int) PressureUnit.MeterOfHead, - new[] - { - new AbbreviationsForCulture("en-US", "m of head"), - }), - new CulturesForEnumValue((int) PressureUnit.Microbar, - new[] - { - new AbbreviationsForCulture("en-US", "µbar"), - new AbbreviationsForCulture("ru-RU", "µбар"), - }), - new CulturesForEnumValue((int) PressureUnit.Micropascal, - new[] - { - new AbbreviationsForCulture("en-US", "µPa"), - new AbbreviationsForCulture("ru-RU", "мкПа"), - }), - new CulturesForEnumValue((int) PressureUnit.Millibar, - new[] - { - new AbbreviationsForCulture("en-US", "mbar"), - new AbbreviationsForCulture("ru-RU", "mбар"), - }), - new CulturesForEnumValue((int) PressureUnit.MillimeterOfMercury, - new[] - { - new AbbreviationsForCulture("en-US", "mmHg"), - }), - new CulturesForEnumValue((int) PressureUnit.Millipascal, - new[] - { - new AbbreviationsForCulture("en-US", "mPa"), - new AbbreviationsForCulture("ru-RU", "ммПа"), - }), - new CulturesForEnumValue((int) PressureUnit.NewtonPerSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/cm²"), - new AbbreviationsForCulture("ru-RU", "Н/см²"), - }), - new CulturesForEnumValue((int) PressureUnit.NewtonPerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/m²"), - new AbbreviationsForCulture("ru-RU", "Н/м²"), - }), - new CulturesForEnumValue((int) PressureUnit.NewtonPerSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/mm²"), - new AbbreviationsForCulture("ru-RU", "Н/мм²"), - }), - new CulturesForEnumValue((int) PressureUnit.Pascal, - new[] - { - new AbbreviationsForCulture("en-US", "Pa"), - new AbbreviationsForCulture("ru-RU", "Па"), - }), - new CulturesForEnumValue((int) PressureUnit.PoundForcePerSquareFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lb/ft²"), - }), - new CulturesForEnumValue((int) PressureUnit.PoundForcePerSquareInch, - new[] - { - new AbbreviationsForCulture("en-US", "psi", "lb/in²"), - }), - new CulturesForEnumValue((int) PressureUnit.PoundPerInchSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "lbm/(in·s²)", "lb/(in·s²)"), - }), - new CulturesForEnumValue((int) PressureUnit.Psi, - new[] - { - new AbbreviationsForCulture("en-US", "psi"), - new AbbreviationsForCulture("ru-RU", "psi"), - }), - new CulturesForEnumValue((int) PressureUnit.TechnicalAtmosphere, - new[] - { - new AbbreviationsForCulture("en-US", "at"), - new AbbreviationsForCulture("ru-RU", "ат"), - }), - new CulturesForEnumValue((int) PressureUnit.TonneForcePerSquareCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/cm²"), - }), - new CulturesForEnumValue((int) PressureUnit.TonneForcePerSquareMeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/m²"), - }), - new CulturesForEnumValue((int) PressureUnit.TonneForcePerSquareMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/mm²"), - }), - new CulturesForEnumValue((int) PressureUnit.Torr, - new[] - { - new AbbreviationsForCulture("en-US", "torr"), - new AbbreviationsForCulture("ru-RU", "торр"), - }), - }), - new UnitLocalization(typeof (PressureChangeRateUnit), - new[] - { - new CulturesForEnumValue((int) PressureChangeRateUnit.AtmospherePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "atm/s"), - new AbbreviationsForCulture("ru-RU", "атм/с"), - }), - new CulturesForEnumValue((int) PressureChangeRateUnit.KilopascalPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "kPa/s"), - new AbbreviationsForCulture("ru-RU", "кПа/с"), - }), - new CulturesForEnumValue((int) PressureChangeRateUnit.MegapascalPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "MPa/s"), - new AbbreviationsForCulture("ru-RU", "МПа/с"), - }), - new CulturesForEnumValue((int) PressureChangeRateUnit.PascalPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "Pa/s"), - new AbbreviationsForCulture("ru-RU", "Па/с"), - }), - }), - new UnitLocalization(typeof (RatioUnit), - new[] - { - new CulturesForEnumValue((int) RatioUnit.DecimalFraction, - new[] - { - new AbbreviationsForCulture("en-US", ""), - }), - new CulturesForEnumValue((int) RatioUnit.PartPerBillion, - new[] - { - new AbbreviationsForCulture("en-US", "ppb"), - }), - new CulturesForEnumValue((int) RatioUnit.PartPerMillion, - new[] - { - new AbbreviationsForCulture("en-US", "ppm"), - }), - new CulturesForEnumValue((int) RatioUnit.PartPerThousand, - new[] - { - new AbbreviationsForCulture("en-US", "‰"), - }), - new CulturesForEnumValue((int) RatioUnit.PartPerTrillion, - new[] - { - new AbbreviationsForCulture("en-US", "ppt"), - }), - new CulturesForEnumValue((int) RatioUnit.Percent, - new[] - { - new AbbreviationsForCulture("en-US", "%"), - }), - }), - new UnitLocalization(typeof (ReactiveEnergyUnit), - new[] - { - new CulturesForEnumValue((int) ReactiveEnergyUnit.KilovoltampereReactiveHour, - new[] - { - new AbbreviationsForCulture("en-US", "kvarh"), - }), - new CulturesForEnumValue((int) ReactiveEnergyUnit.MegavoltampereReactiveHour, - new[] - { - new AbbreviationsForCulture("en-US", "Mvarh"), - }), - new CulturesForEnumValue((int) ReactiveEnergyUnit.VoltampereReactiveHour, - new[] - { - new AbbreviationsForCulture("en-US", "varh"), - }), - }), - new UnitLocalization(typeof (ReactivePowerUnit), - new[] - { - new CulturesForEnumValue((int) ReactivePowerUnit.GigavoltampereReactive, - new[] - { - new AbbreviationsForCulture("en-US", "Gvar"), - }), - new CulturesForEnumValue((int) ReactivePowerUnit.KilovoltampereReactive, - new[] - { - new AbbreviationsForCulture("en-US", "kvar"), - }), - new CulturesForEnumValue((int) ReactivePowerUnit.MegavoltampereReactive, - new[] - { - new AbbreviationsForCulture("en-US", "Mvar"), - }), - new CulturesForEnumValue((int) ReactivePowerUnit.VoltampereReactive, - new[] - { - new AbbreviationsForCulture("en-US", "var"), - }), - }), - new UnitLocalization(typeof (RotationalAccelerationUnit), - new[] - { - new CulturesForEnumValue((int) RotationalAccelerationUnit.DegreePerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "°/s²", "deg/s²"), - }), - new CulturesForEnumValue((int) RotationalAccelerationUnit.RadianPerSecondSquared, - new[] - { - new AbbreviationsForCulture("en-US", "rad/s²"), - }), - new CulturesForEnumValue((int) RotationalAccelerationUnit.RevolutionPerMinutePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "rpm/s"), - }), - }), - new UnitLocalization(typeof (RotationalSpeedUnit), - new[] - { - new CulturesForEnumValue((int) RotationalSpeedUnit.CentiradianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "crad/s"), - new AbbreviationsForCulture("ru-RU", "cрад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.DeciradianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "drad/s"), - new AbbreviationsForCulture("ru-RU", "dрад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.DegreePerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "°/min", "deg/min"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.DegreePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "°/s", "deg/s"), - new AbbreviationsForCulture("ru-RU", "°/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.MicrodegreePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µ°/s"), - new AbbreviationsForCulture("ru-RU", "µ°/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.MicroradianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µrad/s"), - new AbbreviationsForCulture("ru-RU", "µрад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.MillidegreePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m°/s"), - new AbbreviationsForCulture("ru-RU", "m°/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.MilliradianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mrad/s"), - new AbbreviationsForCulture("ru-RU", "mрад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.NanodegreePerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "n°/s"), - new AbbreviationsForCulture("ru-RU", "n°/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.NanoradianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "nrad/s"), - new AbbreviationsForCulture("ru-RU", "nрад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.RadianPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "rad/s"), - new AbbreviationsForCulture("ru-RU", "рад/с"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.RevolutionPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "rpm", "r/min"), - new AbbreviationsForCulture("ru-RU", "об/мин"), - }), - new CulturesForEnumValue((int) RotationalSpeedUnit.RevolutionPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "r/s"), - new AbbreviationsForCulture("ru-RU", "об/с"), - }), - }), - new UnitLocalization(typeof (RotationalStiffnessUnit), - new[] - { - new CulturesForEnumValue((int) RotationalStiffnessUnit.KilonewtonMeterPerRadian, - new[] - { - new AbbreviationsForCulture("en-US", "kN·m/rad"), - }), - new CulturesForEnumValue((int) RotationalStiffnessUnit.MeganewtonMeterPerRadian, - new[] - { - new AbbreviationsForCulture("en-US", "MN·m/rad"), - }), - new CulturesForEnumValue((int) RotationalStiffnessUnit.NewtonMeterPerRadian, - new[] - { - new AbbreviationsForCulture("en-US", "N·m/rad", "Nm/rad"), - }), - }), - new UnitLocalization(typeof (RotationalStiffnessPerLengthUnit), - new[] - { - new CulturesForEnumValue((int) RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN·m/rad/m"), - }), - new CulturesForEnumValue((int) RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN·m/rad/m"), - }), - new CulturesForEnumValue((int) RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, - new[] - { - new AbbreviationsForCulture("en-US", "N·m/rad/m", "Nm/rad/m"), - }), - }), - new UnitLocalization(typeof (SolidAngleUnit), - new[] - { - new CulturesForEnumValue((int) SolidAngleUnit.Steradian, - new[] - { - new AbbreviationsForCulture("en-US", "sr"), - }), - }), - new UnitLocalization(typeof (SpecificEnergyUnit), - new[] - { - new CulturesForEnumValue((int) SpecificEnergyUnit.CaloriePerGram, - new[] - { - new AbbreviationsForCulture("en-US", "cal/g"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.JoulePerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "J/kg"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.KilocaloriePerGram, - new[] - { - new AbbreviationsForCulture("en-US", "kcal/g"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.KilojoulePerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/kg"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.KilowattHourPerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "kWh/kg"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.MegajoulePerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/kg"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.MegawattHourPerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "MWh/kg"), - }), - new CulturesForEnumValue((int) SpecificEnergyUnit.WattHourPerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "Wh/kg"), - }), - }), - new UnitLocalization(typeof (SpecificEntropyUnit), - new[] - { - new CulturesForEnumValue((int) SpecificEntropyUnit.CaloriePerGramKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "cal/g.K"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "J/kg.C"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.JoulePerKilogramKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "J/kg.K"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.KilocaloriePerGramKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "kcal/g.K"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/kg.C"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.KilojoulePerKilogramKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "kJ/kg.K"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/kg.C"), - }), - new CulturesForEnumValue((int) SpecificEntropyUnit.MegajoulePerKilogramKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "MJ/kg.K"), - }), - }), - new UnitLocalization(typeof (SpecificVolumeUnit), - new[] - { - new CulturesForEnumValue((int) SpecificVolumeUnit.CubicFootPerPound, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/lb"), - }), - new CulturesForEnumValue((int) SpecificVolumeUnit.CubicMeterPerKilogram, - new[] - { - new AbbreviationsForCulture("en-US", "m³/kg"), - }), - }), - new UnitLocalization(typeof (SpecificWeightUnit), - new[] - { - new CulturesForEnumValue((int) SpecificWeightUnit.KilogramForcePerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/cm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilogramForcePerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/m³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilogramForcePerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf/mm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilonewtonPerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/cm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilonewtonPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/m³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilonewtonPerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN/mm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilopoundForcePerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kipf/ft³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.KilopoundForcePerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "kipf/in³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.MeganewtonPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN/m³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.NewtonPerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/cm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.NewtonPerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/m³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.NewtonPerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N/mm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.PoundForcePerCubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lbf/ft³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.PoundForcePerCubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "lbf/in³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.TonneForcePerCubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/cm³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.TonneForcePerCubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/m³"), - }), - new CulturesForEnumValue((int) SpecificWeightUnit.TonneForcePerCubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf/mm³"), - }), - }), - new UnitLocalization(typeof (SpeedUnit), - new[] - { - new CulturesForEnumValue((int) SpeedUnit.CentimeterPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "cm/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.CentimeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "cm/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.CentimeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "cm/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.DecimeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "dm/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.DecimeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "dm/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.FootPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "ft/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.FootPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "ft/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.FootPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "ft/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.InchPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "in/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.InchPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "in/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.InchPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "in/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.KilometerPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "km/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.KilometerPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "km/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.KilometerPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "km/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.Knot, - new[] - { - new AbbreviationsForCulture("en-US", "kn", "kt", "knot", "knots"), - }), - new CulturesForEnumValue((int) SpeedUnit.MeterPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "m/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.MeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "m/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.MeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.MicrometerPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "µm/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.MicrometerPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µm/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.MilePerHour, - new[] - { - new AbbreviationsForCulture("en-US", "mph"), - }), - new CulturesForEnumValue((int) SpeedUnit.MillimeterPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "mm/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.MillimeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "mm/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.MillimeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mm/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.NanometerPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "nm/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.NanometerPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "nm/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.UsSurveyFootPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "ftUS/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.UsSurveyFootPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "ftUS/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.UsSurveyFootPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "ftUS/s"), - }), - new CulturesForEnumValue((int) SpeedUnit.YardPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "yd/h"), - }), - new CulturesForEnumValue((int) SpeedUnit.YardPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "yd/min"), - }), - new CulturesForEnumValue((int) SpeedUnit.YardPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "yd/s"), - }), - }), - new UnitLocalization(typeof (TemperatureUnit), - new[] - { - new CulturesForEnumValue((int) TemperatureUnit.DegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "°C"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeDelisle, - new[] - { - new AbbreviationsForCulture("en-US", "°De"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeFahrenheit, - new[] - { - new AbbreviationsForCulture("en-US", "°F"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeNewton, - new[] - { - new AbbreviationsForCulture("en-US", "°N"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeRankine, - new[] - { - new AbbreviationsForCulture("en-US", "°R"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeReaumur, - new[] - { - new AbbreviationsForCulture("en-US", "°Ré"), - }), - new CulturesForEnumValue((int) TemperatureUnit.DegreeRoemer, - new[] - { - new AbbreviationsForCulture("en-US", "°Rø"), - }), - new CulturesForEnumValue((int) TemperatureUnit.Kelvin, - new[] - { - new AbbreviationsForCulture("en-US", "K"), - }), - }), - new UnitLocalization(typeof (TemperatureChangeRateUnit), - new[] - { - new CulturesForEnumValue((int) TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "c°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "da°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "d°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.DegreeCelsiusPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "°C/min"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.DegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "h°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "k°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "µ°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m°C/s"), - }), - new CulturesForEnumValue((int) TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "n°C/s"), - }), - }), - new UnitLocalization(typeof (TemperatureDeltaUnit), - new[] - { - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeCelsius, - new[] - { - new AbbreviationsForCulture("en-US", "∆°C"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeCelsiusDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°C"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeDelisle, - new[] - { - new AbbreviationsForCulture("en-US", "∆°De"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeDelisleDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°De"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeFahrenheit, - new[] - { - new AbbreviationsForCulture("en-US", "∆°F"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeFahrenheitDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°F"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeNewton, - new[] - { - new AbbreviationsForCulture("en-US", "∆°N"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeNewtonDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°N"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeRankine, - new[] - { - new AbbreviationsForCulture("en-US", "∆°R"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeRankineDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°R"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeReaumur, - new[] - { - new AbbreviationsForCulture("en-US", "∆°Ré"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeReaumurDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°Ré"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeRoemer, - new[] - { - new AbbreviationsForCulture("en-US", "∆°Rø"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.DegreeRoemerDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆°Rø"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.Kelvin, - new[] - { - new AbbreviationsForCulture("en-US", "∆K"), - }), - new CulturesForEnumValue((int) TemperatureDeltaUnit.KelvinDelta, - new[] - { - new AbbreviationsForCulture("en-US", "∆K"), - }), - }), - new UnitLocalization(typeof (ThermalConductivityUnit), - new[] - { - new CulturesForEnumValue((int) ThermalConductivityUnit.BtuPerHourFootFahrenheit, - new[] - { - new AbbreviationsForCulture("en-US", "BTU/h·ft·°F"), - }), - new CulturesForEnumValue((int) ThermalConductivityUnit.WattPerMeterKelvin, - new[] - { - new AbbreviationsForCulture("en-US", "W/m·K"), - }), - }), - new UnitLocalization(typeof (ThermalResistanceUnit), - new[] - { - new CulturesForEnumValue((int) ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, - new[] - { - new AbbreviationsForCulture("en-US", "Hrft²°F/Btu"), - }), - new CulturesForEnumValue((int) ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, - new[] - { - new AbbreviationsForCulture("en-US", "cm²Hr°C/kcal"), - }), - new CulturesForEnumValue((int) ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, - new[] - { - new AbbreviationsForCulture("en-US", "cm²K/W"), - }), - new CulturesForEnumValue((int) ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, - new[] - { - new AbbreviationsForCulture("en-US", "m²°C/W"), - }), - new CulturesForEnumValue((int) ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, - new[] - { - new AbbreviationsForCulture("en-US", "m²K/kW"), - }), - }), - new UnitLocalization(typeof (TorqueUnit), - new[] - { - new CulturesForEnumValue((int) TorqueUnit.KilogramForceCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf·cm"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilogramForceMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf·m"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilogramForceMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kgf·mm"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilonewtonCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN·cm"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilonewtonMeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN·m"), - new AbbreviationsForCulture("ru-RU", "кН·м"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilonewtonMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "kN·mm"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilopoundForceFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kipf·ft"), - }), - new CulturesForEnumValue((int) TorqueUnit.KilopoundForceInch, - new[] - { - new AbbreviationsForCulture("en-US", "kipf·in"), - }), - new CulturesForEnumValue((int) TorqueUnit.MeganewtonCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN·cm"), - }), - new CulturesForEnumValue((int) TorqueUnit.MeganewtonMeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN·m"), - new AbbreviationsForCulture("ru-RU", "МН·м"), - }), - new CulturesForEnumValue((int) TorqueUnit.MeganewtonMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "MN·mm"), - }), - new CulturesForEnumValue((int) TorqueUnit.MegapoundForceFoot, - new[] - { - new AbbreviationsForCulture("en-US", "Mlbf·ft"), - }), - new CulturesForEnumValue((int) TorqueUnit.MegapoundForceInch, - new[] - { - new AbbreviationsForCulture("en-US", "Mlbf·in"), - }), - new CulturesForEnumValue((int) TorqueUnit.NewtonCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N·cm"), - }), - new CulturesForEnumValue((int) TorqueUnit.NewtonMeter, - new[] - { - new AbbreviationsForCulture("en-US", "N·m"), - new AbbreviationsForCulture("ru-RU", "Н·м"), - }), - new CulturesForEnumValue((int) TorqueUnit.NewtonMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "N·mm"), - }), - new CulturesForEnumValue((int) TorqueUnit.PoundForceFoot, - new[] - { - new AbbreviationsForCulture("en-US", "lbf·ft"), - }), - new CulturesForEnumValue((int) TorqueUnit.PoundForceInch, - new[] - { - new AbbreviationsForCulture("en-US", "lbf·in"), - }), - new CulturesForEnumValue((int) TorqueUnit.TonneForceCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf·cm"), - }), - new CulturesForEnumValue((int) TorqueUnit.TonneForceMeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf·m"), - }), - new CulturesForEnumValue((int) TorqueUnit.TonneForceMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "tf·mm"), - }), - }), - new UnitLocalization(typeof (VitaminAUnit), - new[] - { - new CulturesForEnumValue((int) VitaminAUnit.InternationalUnit, - new[] - { - new AbbreviationsForCulture("en-US", "IU"), - }), - }), - new UnitLocalization(typeof (VolumeUnit), - new[] - { - new CulturesForEnumValue((int) VolumeUnit.AuTablespoon, - new[] - { - new AbbreviationsForCulture("en-US", ""), - new AbbreviationsForCulture("ru-RU", ""), - new AbbreviationsForCulture("nb-NO", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.Centiliter, - new[] - { - new AbbreviationsForCulture("en-US", "cl"), - new AbbreviationsForCulture("ru-RU", "сл"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicCentimeter, - new[] - { - new AbbreviationsForCulture("en-US", "cm³"), - new AbbreviationsForCulture("ru-RU", "см³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicDecimeter, - new[] - { - new AbbreviationsForCulture("en-US", "dm³"), - new AbbreviationsForCulture("ru-RU", "дм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "ft³"), - new AbbreviationsForCulture("ru-RU", "фут³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicInch, - new[] - { - new AbbreviationsForCulture("en-US", "in³"), - new AbbreviationsForCulture("ru-RU", "дюйм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicKilometer, - new[] - { - new AbbreviationsForCulture("en-US", "km³"), - new AbbreviationsForCulture("ru-RU", "км³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "m³"), - new AbbreviationsForCulture("ru-RU", "м³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicMicrometer, - new[] - { - new AbbreviationsForCulture("en-US", "µm³"), - new AbbreviationsForCulture("ru-RU", "мкм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicMile, - new[] - { - new AbbreviationsForCulture("en-US", "mi³"), - new AbbreviationsForCulture("ru-RU", "миля³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicMillimeter, - new[] - { - new AbbreviationsForCulture("en-US", "mm³"), - new AbbreviationsForCulture("ru-RU", "мм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.CubicYard, - new[] - { - new AbbreviationsForCulture("en-US", "yd³"), - new AbbreviationsForCulture("ru-RU", "ярд³"), - }), - new CulturesForEnumValue((int) VolumeUnit.Deciliter, - new[] - { - new AbbreviationsForCulture("en-US", "dl"), - new AbbreviationsForCulture("ru-RU", "дл"), - }), - new CulturesForEnumValue((int) VolumeUnit.HectocubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "hft³"), - new AbbreviationsForCulture("ru-RU", "hфут³"), - }), - new CulturesForEnumValue((int) VolumeUnit.HectocubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "hm³"), - new AbbreviationsForCulture("ru-RU", "hм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.Hectoliter, - new[] - { - new AbbreviationsForCulture("en-US", "hl"), - new AbbreviationsForCulture("ru-RU", "гл"), - }), - new CulturesForEnumValue((int) VolumeUnit.ImperialBeerBarrel, - new[] - { - new AbbreviationsForCulture("en-US", "bl (imp.)"), - }), - new CulturesForEnumValue((int) VolumeUnit.ImperialGallon, - new[] - { - new AbbreviationsForCulture("en-US", "gal (imp.)"), - new AbbreviationsForCulture("ru-RU", "Английский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.ImperialOunce, - new[] - { - new AbbreviationsForCulture("en-US", "oz (imp.)"), - new AbbreviationsForCulture("ru-RU", "Английская унция"), - }), - new CulturesForEnumValue((int) VolumeUnit.KilocubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "kft³"), - new AbbreviationsForCulture("ru-RU", "kфут³"), - }), - new CulturesForEnumValue((int) VolumeUnit.KilocubicMeter, - new[] - { - new AbbreviationsForCulture("en-US", "km³"), - new AbbreviationsForCulture("ru-RU", "kм³"), - }), - new CulturesForEnumValue((int) VolumeUnit.KiloimperialGallon, - new[] - { - new AbbreviationsForCulture("en-US", "kgal (imp.)"), - new AbbreviationsForCulture("ru-RU", "kАнглийский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.Kiloliter, - new[] - { - new AbbreviationsForCulture("en-US", "kl"), - new AbbreviationsForCulture("ru-RU", "кл"), - }), - new CulturesForEnumValue((int) VolumeUnit.KilousGallon, - new[] - { - new AbbreviationsForCulture("en-US", "kgal (U.S.)"), - new AbbreviationsForCulture("ru-RU", "kАмериканский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.Liter, - new[] - { - new AbbreviationsForCulture("en-US", "l"), - new AbbreviationsForCulture("ru-RU", "л"), - }), - new CulturesForEnumValue((int) VolumeUnit.MegacubicFoot, - new[] - { - new AbbreviationsForCulture("en-US", "Mft³"), - new AbbreviationsForCulture("ru-RU", "Mфут³"), - }), - new CulturesForEnumValue((int) VolumeUnit.MegaimperialGallon, - new[] - { - new AbbreviationsForCulture("en-US", "Mgal (imp.)"), - new AbbreviationsForCulture("ru-RU", "MАнглийский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.MegausGallon, - new[] - { - new AbbreviationsForCulture("en-US", "Mgal (U.S.)"), - new AbbreviationsForCulture("ru-RU", "MАмериканский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.MetricCup, - new[] - { - new AbbreviationsForCulture("en-US", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.MetricTeaspoon, - new[] - { - new AbbreviationsForCulture("en-US", "tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"), - new AbbreviationsForCulture("ru-RU", ""), - new AbbreviationsForCulture("nb-NO", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.Microliter, - new[] - { - new AbbreviationsForCulture("en-US", "µl"), - new AbbreviationsForCulture("ru-RU", "мкл"), - }), - new CulturesForEnumValue((int) VolumeUnit.Milliliter, - new[] - { - new AbbreviationsForCulture("en-US", "ml"), - new AbbreviationsForCulture("ru-RU", "мл"), - }), - new CulturesForEnumValue((int) VolumeUnit.OilBarrel, - new[] - { - new AbbreviationsForCulture("en-US", "bbl"), - }), - new CulturesForEnumValue((int) VolumeUnit.Tablespoon, - new[] - { - new AbbreviationsForCulture("en-US", "Tbsp", "Tbs", "T", "tb", "tbs", "tbsp", "tblsp", "tblspn", "Tbsp.", "Tbs.", "T.", "tb.", "tbs.", "tbsp.", "tblsp.", "tblspn.", "tablespoon", "Tablespoon"), - new AbbreviationsForCulture("ru-RU", "столовая ложка"), - new AbbreviationsForCulture("nb-NO", "ss", "ss.", "SS", "SS."), - }), - new CulturesForEnumValue((int) VolumeUnit.Teaspoon, - new[] - { - new AbbreviationsForCulture("en-US", "tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"), - new AbbreviationsForCulture("ru-RU", "чайная ложка"), - new AbbreviationsForCulture("nb-NO", "ts", "ts."), - }), - new CulturesForEnumValue((int) VolumeUnit.UkTablespoon, - new[] - { - new AbbreviationsForCulture("en-US", ""), - new AbbreviationsForCulture("ru-RU", ""), - new AbbreviationsForCulture("nb-NO", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.UsBeerBarrel, - new[] - { - new AbbreviationsForCulture("en-US", "bl (U.S.)"), - }), - new CulturesForEnumValue((int) VolumeUnit.UsCustomaryCup, - new[] - { - new AbbreviationsForCulture("en-US", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.UsGallon, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)"), - new AbbreviationsForCulture("ru-RU", "Американский галлон"), - }), - new CulturesForEnumValue((int) VolumeUnit.UsLegalCup, - new[] - { - new AbbreviationsForCulture("en-US", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.UsOunce, - new[] - { - new AbbreviationsForCulture("en-US", "oz (U.S.)"), - new AbbreviationsForCulture("ru-RU", "Американская унция"), - }), - new CulturesForEnumValue((int) VolumeUnit.UsPint, - new[] - { - new AbbreviationsForCulture("en-US", "pt (U.S.)"), - }), - new CulturesForEnumValue((int) VolumeUnit.UsQuart, - new[] - { - new AbbreviationsForCulture("en-US", "qt (U.S.)"), - }), - new CulturesForEnumValue((int) VolumeUnit.UsTablespoon, - new[] - { - new AbbreviationsForCulture("en-US", ""), - new AbbreviationsForCulture("ru-RU", ""), - new AbbreviationsForCulture("nb-NO", ""), - }), - new CulturesForEnumValue((int) VolumeUnit.UsTeaspoon, - new[] - { - new AbbreviationsForCulture("en-US", ""), - new AbbreviationsForCulture("ru-RU", ""), - new AbbreviationsForCulture("nb-NO", ""), - }), - }), - new UnitLocalization(typeof (VolumeFlowUnit), - new[] - { - new CulturesForEnumValue((int) VolumeFlowUnit.CentilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "cLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicDecimeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "dm³/min"), - new AbbreviationsForCulture("ru-RU", "дм³/мин"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicFootPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/h", "cf/hr"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicFootPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/min"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicFootPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "ft³/s"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicMeterPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "m³/h"), - new AbbreviationsForCulture("ru-RU", "м³/ч"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicMeterPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "m³/min"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicMeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "m³/s"), - new AbbreviationsForCulture("ru-RU", "м³/с"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicMillimeterPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "mm³/s"), - new AbbreviationsForCulture("ru-RU", "мм³/с"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicYardPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/h"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicYardPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/min"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.CubicYardPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "yd³/s"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.DecilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "dLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.KilolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.KilousGallonsPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "kgal (U.S.)/min", "KGPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.LitersPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "LPH"), - new AbbreviationsForCulture("ru-RU", "л/ч"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.LitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "LPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.LitersPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "LPS"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.MicrolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "µLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.MillilitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "mLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.MillionUsGallonsPerDay, - new[] - { - new AbbreviationsForCulture("en-US", "MGD"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.NanolitersPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "nLPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.OilBarrelsPerDay, - new[] - { - new AbbreviationsForCulture("en-US", "bbl/d", "BOPD"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.OilBarrelsPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "bbl/hr", "bph"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.OilBarrelsPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "bbl/min", "bpm"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.UsGallonsPerHour, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/h"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.UsGallonsPerMinute, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/min", "GPM"), - }), - new CulturesForEnumValue((int) VolumeFlowUnit.UsGallonsPerSecond, - new[] - { - new AbbreviationsForCulture("en-US", "gal (U.S.)/s"), - }), - }), - }); - } -} diff --git a/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs b/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs index c7d465c66b..2b9021f204 100644 --- a/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs index d91272f885..8100f63818 100644 --- a/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs index 2a1b14f392..34fbf79551 100644 --- a/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs b/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs index e87eb277ff..e0685956e2 100644 --- a/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs index 5edcebcffb..d7302fffe5 100644 --- a/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs index 0969f561f4..802534b7ad 100644 --- a/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs index ea36d2a3e4..aef1c8b643 100644 --- a/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs index b455360b49..46e1832024 100644 --- a/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs index 135571a5f7..2530b08548 100644 --- a/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs index 3f614382db..df94d0cdf8 100644 --- a/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs b/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs index 4857a03eca..0ee63f52c1 100644 --- a/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs index a2b8a04b59..1215df419f 100644 --- a/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs b/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs index 540e472988..a9ab3be40f 100644 --- a/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs index 4727857808..9b20e3e13e 100644 --- a/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs b/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs index 5ac31e5143..57b59e4143 100644 --- a/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -50,14 +49,10 @@ public enum DurationUnit Microsecond, Millisecond, Minute, - [System.Obsolete("Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.")] - Month, Month30, Nanosecond, Second, Week, - [System.Obsolete("Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.")] - Year, Year365, } diff --git a/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs b/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs index e8013f83e7..f4cd0a365b 100644 --- a/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs index 45cbd5cb79..56241699b0 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs index a126176d3c..0c895418ba 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs index 9c913a156f..b1a74e6ef5 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs index b6761351a4..4bc13c12b0 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs index 911c4a8c7e..d47b79e70a 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs index 152242cd4c..806746666e 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs index 4037b39966..dd0b12f633 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs index d6fa1465d3..dd9dce6a63 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs index 0a32aa3db6..97eb162198 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs index 25eda23147..fe13141424 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs index 6f8f152361..ac0ac58180 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs index 1aca06144a..c3e26c24b8 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs index 89ed37b2f5..5c7800adbe 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs index 2318179e1e..b03bc94781 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs index ee4288fd78..09d3dedf65 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs index 4a718a8d27..d29480b5e8 100644 --- a/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs index 6e06983b3e..b493323b9b 100644 --- a/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/FlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/FlowUnit.g.cs deleted file mode 100644 index 1cf0e5b07c..0000000000 --- a/UnitsNet/GeneratedCode/Units/FlowUnit.g.cs +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum FlowUnit - { - Undefined = 0, - CentilitersPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicDecimeterPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicFootPerHour, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicFootPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicFootPerSecond, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicMeterPerHour, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicMeterPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicMeterPerSecond, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicYardPerHour, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicYardPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - CubicYardPerSecond, - DecilitersPerMinute, - KilolitersPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - LitersPerHour, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - LitersPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - LitersPerSecond, - MicrolitersPerMinute, - MillilitersPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - MillionUsGallonsPerDay, - NanolitersPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - OilBarrelsPerDay, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - UsGallonsPerHour, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - UsGallonsPerMinute, - [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - UsGallonsPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs index 546be5314c..32eb98ab5f 100644 --- a/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs index d4dc08cf6e..5673df929e 100644 --- a/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs index d3d1d901f0..97ed2c68cf 100644 --- a/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs b/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs index 68f512532f..98d4d43584 100644 --- a/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs index ea98a3b81d..6505998ada 100644 --- a/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs b/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs index cb02c9f7e2..7421fde985 100644 --- a/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs index 28fcead57b..715d90b7a2 100644 --- a/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs b/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs index c31497b843..d9b59e1841 100644 --- a/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs b/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs index b83ad004ad..7a9a483b21 100644 --- a/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs b/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs index 7231cbb235..9248de58bb 100644 --- a/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs b/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs index 1e69957f97..cb8d525fc6 100644 --- a/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs index 7fbba2dd45..f13c5b65c3 100644 --- a/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs index 218be595e1..8da7420323 100644 --- a/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs b/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs index d1524dc87f..0f3441fe14 100644 --- a/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs index b5c66ed948..84ca79123a 100644 --- a/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs index 4625ee4185..0bfa2c6815 100644 --- a/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs index 498896fa94..d5d34cac09 100644 --- a/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs index 764a8f60ed..51a0d07644 100644 --- a/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs index b3e5cafba6..76eb6ee7d4 100644 --- a/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs index d599c500af..46baaadc67 100644 --- a/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs index e9cab9315a..f320c34596 100644 --- a/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs index 5b21271a1c..e801ad4c63 100644 --- a/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs index 1ce72eb279..48269e967a 100644 --- a/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MassUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassUnit.g.cs index 776cea96e8..8fb2ebc11f 100644 --- a/UnitsNet/GeneratedCode/Units/MassUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs index 759d06b3ba..fcb75d0bb9 100644 --- a/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs index 25ca54d2fa..1ba0f0ae63 100644 --- a/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs index d31ab60a5f..80dd9d1374 100644 --- a/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs index 567a931817..4766690daa 100644 --- a/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs index e67d119055..5d8e8033fd 100644 --- a/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs index 2594d47d3b..9693bc2f0c 100644 --- a/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs index 33bc13a7b2..fed2a74c81 100644 --- a/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs index a797980b87..2a2702b85e 100644 --- a/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs index b29758e9ac..7ab0c3d46f 100644 --- a/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs index 7964555547..7cacc7c0bf 100644 --- a/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs index f2c86af5a7..0a5550570a 100644 --- a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -81,8 +80,6 @@ public enum PressureUnit PoundForcePerSquareFoot, PoundForcePerSquareInch, PoundPerInchSecondSquared, - [System.Obsolete("Deprecated due to github issue #215, please use PoundForcePerSquareInch instead")] - Psi, TechnicalAtmosphere, TonneForcePerSquareCentimeter, TonneForcePerSquareMeter, diff --git a/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs index eb6107144c..cdeb18176e 100644 --- a/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs index 7d97715256..f48ea86ece 100644 --- a/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs index 9541472dcb..78f0610799 100644 --- a/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs index 4fc4d56c38..dfd69c5d9b 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs index 14562f4fe9..b5215b9ba1 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs index e8c63c082a..9e15fe4a17 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs index 51f31b86ed..4308f84274 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs b/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs index f187c8988a..79aa7ae5ad 100644 --- a/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs index 6720646ab7..9879456b83 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs index e114267b4f..c58a0a00d7 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs index 9bb8b0d64a..5494f9cdad 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs index 8b40c5726d..4de112c05e 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs index cd9acd74ba..78d4029157 100644 --- a/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs index 6173593193..ea6d2d10e2 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs index 20841be3dd..031ee4369c 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -46,29 +45,13 @@ public enum TemperatureDeltaUnit { Undefined = 0, DegreeCelsius, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeCelsius instead")] - DegreeCelsiusDelta, DegreeDelisle, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeDelisle instead")] - DegreeDelisleDelta, DegreeFahrenheit, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeFahrenheit instead")] - DegreeFahrenheitDelta, DegreeNewton, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeNewton instead")] - DegreeNewtonDelta, DegreeRankine, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRankine instead")] - DegreeRankineDelta, DegreeReaumur, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeReaumur instead")] - DegreeReaumurDelta, DegreeRoemer, - [System.Obsolete("Deprecated due to github issue #180, please use DegreeRoemer instead")] - DegreeRoemerDelta, Kelvin, - [System.Obsolete("Deprecated due to github issue #180, please use Kelvin instead")] - KelvinDelta, } #pragma warning restore 1591 diff --git a/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs index c979602734..6aed814f0b 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs index 95cf039361..9b440faa73 100644 --- a/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs index b45da3be26..d4f267cee8 100644 --- a/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs b/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs index f7b8cf22c5..e8a126324e 100644 --- a/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs b/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs index 7381aa35e0..3563925062 100644 --- a/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs index f28c5aefaf..c8d934cbfb 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -45,7 +44,7 @@ namespace UnitsNet.Units public enum VolumeFlowUnit { Undefined = 0, - CentilitersPerMinute, + CentiliterPerMinute, CubicDecimeterPerMinute, CubicFootPerHour, CubicFootPerMinute, @@ -57,22 +56,22 @@ public enum VolumeFlowUnit CubicYardPerHour, CubicYardPerMinute, CubicYardPerSecond, - DecilitersPerMinute, - KilolitersPerMinute, + DeciliterPerMinute, + KiloliterPerMinute, KilousGallonsPerMinute, - LitersPerHour, - LitersPerMinute, - LitersPerSecond, - MicrolitersPerMinute, - MillilitersPerMinute, + LiterPerHour, + LiterPerMinute, + LiterPerSecond, + MicroliterPerMinute, + MilliliterPerMinute, MillionUsGallonsPerDay, - NanolitersPerMinute, - OilBarrelsPerDay, - OilBarrelsPerHour, - OilBarrelsPerMinute, - UsGallonsPerHour, - UsGallonsPerMinute, - UsGallonsPerSecond, + NanoliterPerMinute, + OilBarrelPerDay, + OilBarrelPerHour, + OilBarrelPerMinute, + UsGallonPerHour, + UsGallonPerMinute, + UsGallonPerSecond, } #pragma warning restore 1591 diff --git a/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs index acb562415e..2cba36be1d 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs @@ -9,8 +9,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -78,10 +77,6 @@ public enum VolumeUnit Microliter, Milliliter, OilBarrel, - [System.Obsolete("Deprecated due to github issue #134, please use UsTablespoon instead")] - Tablespoon, - [System.Obsolete("Deprecated due to github issue #134, please use UsTeaspoon instead")] - Teaspoon, UkTablespoon, UsBeerBarrel, UsCustomaryCup, diff --git a/UnitsNet/I18n/AbbreviationsForCulture.cs b/UnitsNet/I18n/AbbreviationsForCulture.cs deleted file mode 100644 index beef5b0918..0000000000 --- a/UnitsNet/I18n/AbbreviationsForCulture.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.Collections.ObjectModel; -using System.Globalization; -using System.Linq; - -namespace UnitsNet.I18n -{ - internal class AbbreviationsForCulture - { - public readonly ReadOnlyCollection Abbreviations; - public readonly CultureInfo Cult; - - public AbbreviationsForCulture(string cultureName, params string[] abbreviations) - { - Cult = new CultureInfo(cultureName); - Abbreviations = new ReadOnlyCollection(abbreviations.ToList()); - } - } -} \ No newline at end of file diff --git a/UnitsNet/I18n/CulturesForEnumValue.cs b/UnitsNet/I18n/CulturesForEnumValue.cs deleted file mode 100644 index 981c099095..0000000000 --- a/UnitsNet/I18n/CulturesForEnumValue.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace UnitsNet.I18n -{ - internal class CulturesForEnumValue - { - public readonly ReadOnlyCollection Cultures; - public readonly int Value; - - public CulturesForEnumValue(int value, IEnumerable cultures) - { - Value = value; - Cultures = new ReadOnlyCollection(cultures.ToList()); - } - } -} \ No newline at end of file diff --git a/UnitsNet/I18n/UnitLocalization.cs b/UnitsNet/I18n/UnitLocalization.cs deleted file mode 100644 index 0f9879a89e..0000000000 --- a/UnitsNet/I18n/UnitLocalization.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace UnitsNet.I18n -{ - internal class UnitLocalization - { - public readonly ReadOnlyCollection EnumValues; - public readonly Type UnitEnumType; - - public UnitLocalization(Type unitEnumType, IEnumerable enumValues) - { - UnitEnumType = unitEnumType; - EnumValues = new ReadOnlyCollection(enumValues.ToList()); - } - } -} \ No newline at end of file diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index e49f7f7ee3..2b499f4507 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -19,12 +19,15 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +using System; +using JetBrains.Annotations; + namespace UnitsNet { /// /// Represents a quantity. /// - public interface IQuantity + public partial interface IQuantity { /// /// The of this quantity. @@ -42,4 +45,85 @@ BaseDimensions Dimensions get; } } + +#if !WINDOWS_UWP + + public partial interface IQuantity + { + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. + /// Format to use for localization and number formatting. Defaults to if null. + string ToString([CanBeNull] 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. + string ToString([CanBeNull] 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. + string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args); + } + +#else + + public partial interface IQuantity + { + /// + /// 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); + } + +#endif + +#if !WINDOWS_UWP + + public interface IQuantity : IQuantity where UnitType : Enum + { + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + double As(UnitType unit); + + /// + /// The unit this quantity was constructed with or the BaseUnit if the default constructor was used. + /// + UnitType Unit + { + get; + } + } + +#endif } diff --git a/UnitsNet/CustomCode/Extensions/PowerExtensions.cs b/UnitsNet/InternalHelpers/Guard.cs similarity index 53% rename from UnitsNet/CustomCode/Extensions/PowerExtensions.cs rename to UnitsNet/InternalHelpers/Guard.cs index e57d18ebd2..9a30d55ecc 100644 --- a/UnitsNet/CustomCode/Extensions/PowerExtensions.cs +++ b/UnitsNet/InternalHelpers/Guard.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,25 +19,29 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -namespace UnitsNet.CustomCode.Extensions +using System; +using JetBrains.Annotations; + +namespace UnitsNet.InternalHelpers { /// - /// Extension methods for . + /// Guard methods to ensure parameter values satisfy pre-conditions and use a consistent exception message. /// - public static class PowerExtensions + internal static class Guard { /// - /// Gets a from a relative to one watt. + /// Throws if value is , + /// or . /// - /// - /// Provides a nicer syntax for converting a power to a power ratio (relative to 1 watt). - /// - /// var powerRatio = power.ToPowerRatio(); - /// - /// - public static PowerRatio ToPowerRatio(this Power power) + /// 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) { - return PowerRatio.FromPower(power); + 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; } } -} \ No newline at end of file +} diff --git a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs index 85138d716f..993f389f96 100644 --- a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs +++ b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs @@ -24,11 +24,7 @@ using System.Collections.Generic; using System.Reflection; -#if SIGNED -[assembly: InternalsVisibleTo("UnitsNet.Serialization.JsonNet.Signed, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] -#else -[assembly: InternalsVisibleTo("UnitsNet.Serialization.JsonNet")] -#endif +[assembly: InternalsVisibleTo("UnitsNet.Serialization.JsonNet, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] // Based on // https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs diff --git a/UnitsNet/Length2d.cs b/UnitsNet/Length2d.cs deleted file mode 100644 index e3e19d7c04..0000000000 --- a/UnitsNet/Length2d.cs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if !WINDOWS_UWP -using System; -using System.Collections.Generic; -using UnitsNet.Units; - -#endif - -namespace UnitsNet -{ - /// - /// A class for representing position in two dimensions. - /// -#if WINDOWS_UWP - public struct Length2d - { - /// - /// Returns a point represented in meters. - /// - public Vector2 Meters; - } -#else - public struct Length2d : IEquatable - { - /// - /// Returns a point represented in meters. - /// - public readonly Vector2 Meters; - - /// - /// Creates an instance based on X and Y in implicitly defined SI units. - /// - public Length2d(double xMeters, double yMeters) - { - Meters = new Vector2(xMeters, yMeters); - } - - public Length2d(Length x, Length y) : this(x.Meters, y.Meters) - { - } - - #region Static - - public static Length GetDistance(Length2d a, Length2d b) - { - Vector2 d = (a - b).Meters; - return Length.FromMeters(Math.Sqrt(d.X*d.X + d.Y*d.Y)); - } - - #endregion - - #region Public properties - - public Length Length - { - get - { - double x = Meters.X; - double y = Meters.Y; - return Length.FromMeters(Math.Sqrt(x*x + y*y)); - } - } - - public Length X => Length.FromMeters(Meters.X); - - public Length Y => Length.FromMeters(Meters.Y); - - public Vector2 Miles => new Vector2(X.Miles, Y.Miles); - - public Vector2 Yards => new Vector2(X.Yards, Y.Yards); - - public Vector2 Feet => new Vector2(X.Feet, Y.Feet); - - public Vector2 Inches => new Vector2(X.Inches, Y.Inches); - - public Vector2 Kilometers => new Vector2(X.Kilometers, Y.Kilometers); - - public Vector2 Decimeters => new Vector2(X.Decimeters, Y.Decimeters); - - /// - /// Returns a point represented in centimeters. - /// - public Vector2 Centimeters => new Vector2(Meters.X*1E2, Meters.Y*1E2); - - /// - /// Returns a point represented in millimeters. - /// - public Vector2 Millimeters => new Vector2(Meters.X*1E3, Meters.Y*1E3); - - public Vector2 Micrometers => new Vector2(X.Micrometers, Y.Micrometers); - - public Vector2 Nanometers => new Vector2(X.Nanometers, Y.Nanometers); - - #endregion - - #region Static methods - - public static Length2d Zero => new Length2d(); - - public static Length2d FromMeters(double xMeters, double yMeters) - { - return new Length2d(xMeters, yMeters); - } - - public static Length2d FromCentimeters(double xCentimeters, double yCentimeters) - { - return new Length2d(xCentimeters*1E-2, yCentimeters*1E-2); - } - - public static Length2d FromMillimeters(double xMillimeters, double yMillimeters) - { - return new Length2d(xMillimeters*1E-3, yMillimeters*1E-3); - } - - #endregion - - #region Arithmetic operators - - public static Length2d operator -(Length2d right) - { - return FromMeters(-right.X.Meters, -right.Y.Meters); - } - - public static Length2d operator +(Length2d left, Length2d right) - { - double x = left.X.Meters + right.X.Meters; - double y = left.Y.Meters + right.Y.Meters; - return FromMeters(x, y); - } - - public static Length2d operator -(Length2d left, Length2d right) - { - double x = left.X.Meters - right.X.Meters; - double y = left.Y.Meters - right.Y.Meters; - return FromMeters(x, y); - } - - public static Length2d operator *(double left, Length2d right) - { - double x = left*right.X.Meters; - double y = left*right.Y.Meters; - return FromMeters(x, y); - } - - public static Length2d operator *(Length2d left, double right) - { - double x = left.X.Meters*right; - double y = left.Y.Meters*right; - return FromMeters(x, y); - } - - public static Length2d operator *(Length2d left, Length2d right) - { - double x = left.X.Meters*right.X.Meters; - double y = left.Y.Meters*right.Y.Meters; - return FromMeters(x, y); - } - - public static Length2d operator /(Length2d left, double right) - { - double x = left.X.Meters/right; - double y = left.Y.Meters/right; - return FromMeters(x, y); - } - - public static Vector2 operator /(Length2d left, Length2d right) - { - double x = left.X.Meters/right.X.Meters; - double y = left.Y.Meters/right.Y.Meters; - return new Vector2(x, y); - } - - #endregion - - #region Public methods - - public override string ToString() - { - return - $"({X.Meters:0.##}, {Y.Meters:0.##}) {UnitSystem.GetCached().GetDefaultAbbreviation(LengthUnit.Meter)}"; - } - - public Length DistanceTo(Length2d other) - { - double dx = X.Meters - other.X.Meters; - double dy = Y.Meters - other.Y.Meters; - double distance = Math.Sqrt(dx*dx + dy*dy); - - return Length.FromMeters(distance); - } - - #endregion - - #region Equality - - private static IEqualityComparer MetersComparer { get; } = new MetersEqualityComparer(); - - public bool Equals(Length2d other) - { - return MetersComparer.Equals(this, other); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is Length2d && Equals((Length2d) obj); - } - - public override int GetHashCode() - { - return Meters.GetHashCode(); - } - - public static bool operator !=(Length2d left, Length2d right) - { - return left.Meters != right.Meters; - } - - public static bool operator ==(Length2d left, Length2d right) - { - return left.Meters == right.Meters; - } - - private sealed class MetersEqualityComparer : IEqualityComparer - { - public bool Equals(Length2d x, Length2d y) - { - return x.Meters.Equals(y.Meters); - } - - public int GetHashCode(Length2d obj) - { - return obj.Meters.GetHashCode(); - } - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/UnitsNet/Properties/AssemblyInfo.WindowsRuntimeComponent.cs b/UnitsNet/Properties/AssemblyInfo.WindowsRuntimeComponent.cs index e3e56cc29a..4bfa15e002 100644 --- a/UnitsNet/Properties/AssemblyInfo.WindowsRuntimeComponent.cs +++ b/UnitsNet/Properties/AssemblyInfo.WindowsRuntimeComponent.cs @@ -38,6 +38,6 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("")] -[assembly: AssemblyVersion("3.111.0")] -[assembly: AssemblyFileVersion("3.111.0")] +[assembly: AssemblyVersion("4.0.0")] +[assembly: AssemblyFileVersion("4.0.0")] [assembly: InternalsVisibleTo("UnitsNet.WindowsRuntimeComponent.Tests")] diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index 2998dc148c..2838e37c50 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -21,9 +21,9 @@ // Operator overloads not supported in Windows Runtime Components, we use 'double' type instead -#if !WINDOWS_UWP -using System; +using UnitsNet.InternalHelpers; +#if !WINDOWS_UWP namespace UnitsNet { /// @@ -57,7 +57,7 @@ public struct QuantityValue private QuantityValue(double val) { - _value = val; + _value = Guard.EnsureValidNumber(val, nameof(val)); _valueDecimal = null; } diff --git a/UnitsNet/Scripts/GenerateUnits.ps1 b/UnitsNet/Scripts/GenerateUnits.ps1 index b588817d2c..1b305d79a5 100644 --- a/UnitsNet/Scripts/GenerateUnits.ps1 +++ b/UnitsNet/Scripts/GenerateUnits.ps1 @@ -1,4 +1,8 @@ -# Set Write-Output used by Include- files to UTF8 encoding to fix copyright character +using module ".\Types.psm1" + +#Requires -Version 5.1 + +# Set Write-Output used by Include- files to UTF8 encoding to fix copyright character [Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8 $OutputEncoding = [Text.UTF8Encoding]::UTF8 @@ -8,32 +12,24 @@ function ToCamelCase($str) return $str.Substring(0,1).ToLowerInvariant() + $str.Substring(1) } +function ValueOrDefault($value, $defaultValue){ + if ($value -ne $null) { $value } else { $defaultValue } +} -function GenerateQuantity($quantity, $outDir) +function GenerateQuantity([Quantity]$quantity, $outDir) { - $outFileName = "$outDir/../../../Common/GeneratedCode/Quantities/$($quantity.Name).Common.g.cs" - GenerateQuantitySourceCodeCommon $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } - Write-Host -NoNewline "quantity common(OK) " - $outFileName = "$outDir/$($quantity.Name).NetFramework.g.cs" - GenerateQuantitySourceCodeNetFramework $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } + GenerateQuantitySourceCodeNetFramework $quantity "NetFramework" | Out-File -Encoding "UTF8" $outFileName | Out-Null + if (!$?) { exit 1 } Write-Host -NoNewline "quantity .NET(OK) " $outFileName = "$outDir/../../../UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/$($quantity.Name).WindowsRuntimeComponent.g.cs" - GenerateQuantitySourceCodeWindowsRuntimeComponent $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null - if (!$?) { - exit 1 - } + GenerateQuantitySourceCodeNetFramework $quantity "WindowsRuntimeComponent" | Out-File -Encoding "UTF8" $outFileName | Out-Null + if (!$?) { exit 1 } Write-Host -NoNewline "quantity WRC(OK) " } -function GenerateUnitTestBaseClass($quantity, $outDir) +function GenerateUnitTestBaseClass([Quantity]$quantity, $outDir) { $outFileName = "$outDir/$($quantity.Name)TestsBase.g.cs" GenerateUnitTestBaseClassSourceCode $quantity | Out-File -Encoding "UTF8" $outFileName | Out-Null @@ -43,7 +39,7 @@ function GenerateUnitTestBaseClass($quantity, $outDir) Write-Host -NoNewline "test base(OK) " } -function GenerateUnitTestClassIfNotExists($quantity, $outDir) +function GenerateUnitTestClassIfNotExists([Quantity]$quantity, $outDir) { Write-Host -NoNewline "test stub" $outFileName = "$outDir/$($quantity.Name)Tests.cs" @@ -62,7 +58,7 @@ function GenerateUnitTestClassIfNotExists($quantity, $outDir) } } -function GenerateUnitType($quantity, $outDir) +function GenerateUnitType([Quantity]$quantity, $outDir) { $outFileName = "$outDir/$($quantity.Name)Unit.g.cs" @@ -75,8 +71,8 @@ function GenerateUnitType($quantity, $outDir) function GenerateUnitSystemDefault($quantities, $outDir) { - Write-Host -NoNewline "UnitSystem.Default.g.cs: " - $outFileName = "$outDir/UnitSystem.Default.g.cs" + Write-Host -NoNewline "UnitAbbreviationsCache.g.cs: " + $outFileName = "$outDir/UnitAbbreviationsCache.g.cs" GenerateUnitSystemDefaultSourceCode $quantities | Out-File -Encoding "UTF8" -Force $outFileName | Out-Null if (!$?) { @@ -99,22 +95,6 @@ function GenerateQuantityType($quantities, $outDir) Write-Host "(OK) " } -function GenerateNumberExtensions($quantity, $numberExtensionsDir) -{ - $outDir = "$numberExtensionsDir" - $fileName = "NumberTo$($quantity.Name)Extensions.g.cs" - $outFilePath = "$outDir/$fileName" - EnsureDirExists $outDir - Write-Host -NoNewline "NumberExtensions" - - GenerateNumberExtensionsSourceCode $quantity | Out-File -Encoding "UTF8" -Force $outFilePath | Out-Null - if (!$?) { - Write-Host -NoNewline "(error) " - exit 1 - } - Write-Host -NoNewline "(OK) " -} - function EnsureDirExists([String] $dirPath) { New-Item -ItemType Directory -Force -Path $dirPath | Out-Null if (!$?) { @@ -122,26 +102,6 @@ function EnsureDirExists([String] $dirPath) { } } -function Set-DefaultValues { - param ([Parameter(Mandatory = $true, ValueFromPipeline=$true)] $quantity) - PROCESS { - if (!$quantity.BaseType) { - $quantity | Add-Member BaseType "double" - } - if ($quantity.GenerateArithmetic -eq $null) { - $quantity | Add-Member GenerateArithmetic $true - } - # 'Logarithmic' is optional in the .json file and assumed to be false if not specified - if (!$quantity.Logarithmic) { - $quantity | Add-Member Logarithmic $false - } - elseif (!$quantity.LogarithmicScalingFactor) { - $quantity | Add-Member LogarithmicScalingFactor 1 - } - return $quantity - } -} - function Set-ConversionFunctions { param ([Parameter(Mandatory = $true, ValueFromPipeline=$true)] $quantity) @@ -255,7 +215,7 @@ function Set-UnitsOrderedByName { } } -function Add-InheritedUnits($quantity, $quantities) { +function Add-InheritedUnits([Quantity]$quantity, $quantities) { foreach ($inheritFromQuantityName in $quantity.InheritUnitsFrom) { $inheritFromQuantity = $quantities | Where { $_.Name -eq $inheritFromQuantityName } | Select -First 1 @@ -267,13 +227,9 @@ function Add-InheritedUnits($quantity, $quantities) { # Load external generator functions with same name as file . "$PSScriptRoot/Include-GenerateTemplates.ps1" -. "$PSScriptRoot/Include-GenerateLogarithmicCode.ps1" -. "$PSScriptRoot/Include-GenerateNumberExtensionsSourceCode.ps1" . "$PSScriptRoot/Include-GenerateUnitSystemDefaultSourceCode.ps1" . "$PSScriptRoot/Include-GenerateQuantityTypeSourceCode.ps1" -. "$PSScriptRoot/Include-GenerateQuantitySourceCodeCommon.ps1" . "$PSScriptRoot/Include-GenerateQuantitySourceCodeNetFramework.ps1" -. "$PSScriptRoot/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1" . "$PSScriptRoot/Include-GenerateUnitTypeSourceCode.ps1" . "$PSScriptRoot/Include-GenerateUnitTestBaseClassSourceCode.ps1" . "$PSScriptRoot/Include-GenerateUnitTestPlaceholderSourceCode.ps1" @@ -282,17 +238,59 @@ EnsureDirExists ($quantityDir = "$PSScriptRoot/../GeneratedCode/Quantities") EnsureDirExists ($unitEnumDir = "$PSScriptRoot/../GeneratedCode/Units") EnsureDirExists ($unitSystemDir = "$PSScriptRoot/../GeneratedCode") EnsureDirExists ($testsDir = "$PSScriptRoot/../../UnitsNet.Tests/GeneratedCode") -EnsureDirExists ($numberExtensionsDir = "$PSScriptRoot/../GeneratedCode/Extensions/Number") EnsureDirExists ($testsCustomCodeDir = "$PSScriptRoot/../../UnitsNet.Tests/CustomCode") $templatesDir = "$PSScriptRoot/../../Common/UnitDefinitions" $pad = 25 -# Parse unit definitions from .json files and populate properties +# Parse unit definitions from .json files +# TODO Find a way to automap from JSON into Quantity type $quantities = Get-ChildItem -Path $templatesDir -filter "*.json" ` | %{(Get-Content $_.FullName -Encoding "UTF8" | Out-String)} ` | ConvertFrom-Json ` - | Set-DefaultValues ` + | %{ + # $_ | fl | out-string | write-host -foreground blue + # New-Object -TypeName Quantity -Verbose -Property @{ + [Quantity]@{ + Name = $_.Name + XmlDocSummary = $_.XmlDoc + XmlDocRemarks = $_.XmlDocRemarks + BaseUnit = $_.BaseUnit + BaseType = ValueOrDefault $_.BaseType "double" + BaseDimensions = @{ + Length = ValueOrDefault $_.BaseDimensions.L 0 + Mass = ValueOrDefault $_.BaseDimensions.M 0 + Time = ValueOrDefault $_.BaseDimensions.T 0 + ElectricCurrent = ValueOrDefault $_.BaseDimensions.I 0 + Temperature = ValueOrDefault $_.BaseDimensions.Θ 0 + AmountOfSubstance = ValueOrDefault $_.BaseDimensions.N 0 + LuminousIntensity = ValueOrDefault $_.BaseDimensions.J 0 + } + GenerateArithmetic = ValueOrDefault $_.GenerateArithmetic $true + Logarithmic = ValueOrDefault $_.Logarithmic $false + LogarithmicScalingFactor = ValueOrDefault $_.LogarithmicScalingFactor 1 + Units = $_.Units | %{ + # $_ | fl | out-string | Write-Host -ForegroundColor blue + [Unit]@{ + SingularName = $_.SingularName + PluralName = $_.PluralName + XmlDocSummary = $_.XmlDocSummary + XmlDocRemarks = $_.XmlDocRemarks + FromUnitToBaseFunc = $_.FromUnitToBaseFunc + FromBaseToUnitFunc = $_.FromBaseToUnitFunc + Prefixes = [string[]](ValueOrDefault $_.Prefixes @()) + Localization = $_.Localization | %{ + # $_ | fl | out-string | Write-Host -ForegroundColor blue + [Localization]@{ + Culture = $_.Culture + Abbreviations = $_.Abbreviations + AbbreviationsWithPrefixes = $_.AbbreviationsWithPrefixes + } + } + } + } + } + } ` | Add-PrefixUnits ` | Set-ConversionFunctions ` | Set-UnitsOrderedByName @@ -304,7 +302,6 @@ foreach ($quantity in $quantities) { GenerateQuantity $quantity $quantityDir GenerateUnitType $quantity $unitEnumDir - GenerateNumberExtensions $quantity $numberExtensionsDir GenerateUnitTestBaseClass $quantity $testsDir GenerateUnitTestClassIfNotExists $quantity $testsCustomCodeDir diff --git a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 b/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 deleted file mode 100644 index ba7a62c49f..0000000000 --- a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 +++ /dev/null @@ -1,72 +0,0 @@ -<# -.SYNOPSIS -Generates the C# source code for logarithmic arithmetic operators. - -.PARAMETER quantityName -The name of the unit. - -.PARAMETER baseUnitFieldName -The name of the backing field used to store the unit's value. - -.PARAMETER baseType -The data type of the backing field used to store the unit's value. - -.PARAMETER scalingFactor -The scaling factor used in logarithmic calculations. In most cases this is equal to 1. -#> -function GenerateLogarithmicArithmeticOperators([string]$quantityName, [string]$baseUnitFieldName, [string]$baseType, [int]$scalingFactor) -{ - # Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to - # use 20 instead of 10. - $x = 10 * $scalingFactor; - -@" - - #region Logarithmic Arithmetic Operators - - public static $quantityName operator -($quantityName right) - { - return new $quantityName(-right.Value, right.Unit); - } - - public static $quantityName operator +($quantityName left, $quantityName right) - { - // Logarithmic addition - // Formula: $x*log10(10^(x/$x) + 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); - } - - public static $quantityName operator -($quantityName left, $quantityName right) - { - // Logarithmic subtraction - // Formula: $x*log10(10^(x/$x) - 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); - } - - public static $quantityName operator *($baseType left, $quantityName right) - { - // Logarithmic multiplication = addition - return new $quantityName(left + right.Value, right.Unit); - } - - public static $quantityName operator *($quantityName left, double right) - { - // Logarithmic multiplication = addition - return new $quantityName(left.Value + ($baseType)right, left.Unit); - } - - public static $quantityName operator /($quantityName left, double right) - { - // Logarithmic division = subtraction - return new $quantityName(left.Value - ($baseType)right, left.Unit); - } - - public static double operator /($quantityName left, $quantityName right) - { - // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); - } - - #endregion -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateNumberExtensionsSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateNumberExtensionsSourceCode.ps1 deleted file mode 100644 index 2c931d79f1..0000000000 --- a/UnitsNet/Scripts/Include-GenerateNumberExtensionsSourceCode.ps1 +++ /dev/null @@ -1,79 +0,0 @@ -function GenerateNumberExtensionsSourceCode($quantity) -{ - $quantityName = $quantity.Name; - $units = $quantity.Units; -@" -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -// Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if !WINDOWS_UWP -namespace UnitsNet.Extensions.NumberTo$quantityName -{ - public static class NumberTo$($quantityName)Extensions - { -"@; foreach ($unit in $units) { - $obsoleteAttribute = GetObsoleteAttribute($unit); - if ($obsoleteAttribute) - { - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page - } - - # A few units share the exact same name across quantities, which give extension method name conflicts. - # We add "OmitExtensionMethod": true on all but one of the conflicting units in JSON. - if ($unit.OmitExtensionMethod) { continue } -@" - #region $($unit.SingularName) - - /// $($obsoleteAttribute) - public static $quantityName $($unit.PluralName)(this T value) => $quantityName.From$($unit.PluralName)(Convert.ToDouble(value)); - - /// - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static $($quantityName)? $($unit.PluralName)(this T? value) where T : struct => $quantityName.From$($unit.PluralName)(value == null ? (double?)null : Convert.ToDouble(value.Value)); - - #endregion - -"@; }@" - } -} -#endif -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 deleted file mode 100644 index 7a19d54147..0000000000 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeCommon.ps1 +++ /dev/null @@ -1,571 +0,0 @@ -function GenerateQuantitySourceCodeCommon($quantity) -{ - $quantityName = $quantity.Name; - $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } - $baseUnitSingularName = $baseUnit.SingularName - $baseUnitPluralName = $baseUnit.PluralName - $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() - $unitEnumName = "$quantityName" + "Unit" - - # Base dimensions - $baseDimensions = $quantity.BaseDimensions; - $baseDimensionLength = if($baseDimensions.L){$baseDimensions.L} else{0}; - $baseDimensionMass = if($baseDimensions.M){$baseDimensions.M} else{0}; - $baseDimensionTime = if($baseDimensions.T){$baseDimensions.T} else{0}; - $baseDimensionElectricCurrent = if($baseDimensions.I){$baseDimensions.I} else{0}; - $baseDimensionTemperature = if($baseDimensions.Θ){$baseDimensions.Θ} else{0}; - $baseDimensionAmountOfSubstance = if($baseDimensions.N){$baseDimensions.N} else{0}; - $baseDimensionLuminousIntensity = if($baseDimensions.J){$baseDimensions.J} else{0}; - - $convertToBaseType = switch ($baseType) { - "long" { "Convert.ToInt64"; break } - "double" { "Convert.ToDouble"; break } - "decimal" { "Convert.ToDecimal"; break } - default { throw "Base type not supported: $baseType" } - } - - $quantityValueType = switch ($baseType) { - "long" { "QuantityValue"; break } - "double" { "QuantityValue"; break } - "decimal" { "QuantityValue"; break } - default { throw "Base type not supported: $baseType" } - } - - $obsoleteEqualityIfDouble = '' - if ($quantity.BaseType -eq "double") { - $obsoleteEqualityIfDouble = "[Obsolete(`"It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals($quantityName, double, ComparisonType) to provide the max allowed absolute or relative error.`")]`r`n " - } - -@" -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ -"@; -$obsoleteAttribute = GetObsoleteAttribute($quantity); -if ($obsoleteAttribute) -{ - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this section -} -@" - /// - /// $($quantity.XmlDoc) - /// - // ReSharper disable once PartialTypeWithSinglePart$($obsoleteAttribute) - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class $quantityName : IQuantity -#else - public partial struct $quantityName : IQuantity, IComparable, IComparable<$quantityName> -#endif - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly $baseType _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly $($unitEnumName)? _unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public $unitEnumName Unit => _unit.GetValueOrDefault(BaseUnit); - - static $quantityName() - { -"@; - if($baseDimensions) - { -@" - BaseDimensions = new BaseDimensions($baseDimensionLength, $baseDimensionMass, $baseDimensionTime, $baseDimensionElectricCurrent, $baseDimensionTemperature, $baseDimensionAmountOfSubstance, $baseDimensionLuminousIntensity); -"@; - } -@" - } - - /// - /// Creates the quantity with the given value in the base unit $baseUnitSingularName. - /// - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public $quantityName(double $baseUnitPluralNameLower) - { - _value = $convertToBaseType($baseUnitPluralNameLower); - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// Numeric value. - /// Unit representation. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. -#if WINDOWS_UWP - private -#else - public -#endif - $quantityName($baseType numericValue, $unitEnumName unit) - { - _value = numericValue; - _unit = 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 - /// - /// Creates the quantity with the given value assuming the base unit $baseUnitSingularName. - /// - /// Value assuming base unit $baseUnitSingularName. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - $quantityName(long $baseUnitPluralNameLower) : this($convertToBaseType($baseUnitPluralNameLower), BaseUnit) { } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - // Windows Runtime Component does not support decimal type - /// - /// Creates the quantity with the given value assuming the base unit $baseUnitSingularName. - /// - /// Value assuming base unit $baseUnitSingularName. -#if WINDOWS_UWP - private -#else - [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] - public -#endif - $quantityName(decimal $baseUnitPluralNameLower) : this($convertToBaseType($baseUnitPluralNameLower), BaseUnit) { } - - #region Properties - - /// - /// The of this quantity. - /// - public static QuantityType QuantityType => QuantityType.$quantityName; - - /// - /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. - /// - public static $unitEnumName BaseUnit => $unitEnumName.$baseUnitSingularName; - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions - { - get; - } - - /// - /// All units of measurement for the $quantityName quantity. - /// - public static $unitEnumName[] Units { get; } = Enum.GetValues(typeof($unitEnumName)).Cast<$unitEnumName>().Except(new $unitEnumName[]{ $unitEnumName.Undefined }).ToArray(); -"@; - foreach ($unit in $units) { - $propertyName = $unit.PluralName; - $obsoleteAttribute = GetObsoleteAttribute($unit); - if ($obsoleteAttribute) - { - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page - } -@" - - /// - /// Get $quantityName in $propertyName. - /// $($obsoleteAttribute) - public double $propertyName => As($unitEnumName.$($unit.SingularName)); -"@; }@" - - #endregion - - #region Static - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit $baseUnitSingularName. - /// - public static $quantityName Zero => new $quantityName(0, BaseUnit); - -"@; foreach ($unit in $units) { - $valueParamName = $unit.PluralName.ToLowerInvariant(); - $obsoleteAttribute = GetObsoleteAttribute($unit); - if ($obsoleteAttribute) - { - $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page - } -@" - /// - /// Get $quantityName from $($unit.PluralName). - /// $($obsoleteAttribute) -#if WINDOWS_UWP - [Windows.Foundation.Metadata.DefaultOverload] - public static $quantityName From$($unit.PluralName)(double $valueParamName) -#else - public static $quantityName From$($unit.PluralName)($quantityValueType $valueParamName) -#endif - { - $baseType value = ($baseType) $valueParamName; - return new $quantityName(value, $unitEnumName.$($unit.SingularName)); - } - -"@; }@" - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// $quantityName unit value. -#if WINDOWS_UWP - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static $quantityName From(double value, $unitEnumName fromUnit) -#else - public static $quantityName From($quantityValueType value, $unitEnumName fromUnit) -#endif - { - return new $quantityName(($baseType)value, fromUnit); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit) - { - return GetAbbreviation(unit, null); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if(obj is null) throw new ArgumentNullException(nameof(obj)); - if(!(obj is $quantityName)) throw new ArgumentException("Expected type $quantityName.", nameof(obj)); - - return CompareTo(($quantityName)obj); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods -#if WINDOWS_UWP - internal -#else - public -#endif - int CompareTo($quantityName other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - $($obsoleteEqualityIfDouble)public override bool Equals(object obj) - { - if(obj is null || !(obj is $quantityName)) - return false; - - var objQuantity = ($quantityName)obj; - return _value.Equals(objQuantity.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another $quantityName within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals($quantityName other, double tolerance, ComparisonType comparisonType) - { - if(tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Compare equality to another $quantityName by specifying a max allowed difference. - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// Other quantity to compare to. - /// Max error allowed. - /// True if the difference between the two values is not greater than the specified max. - [Obsolete("Please use the Equals($quantityName, double, ComparisonType) overload. This method will be removed in a future version.")] - public bool Equals($quantityName other, $quantityName maxError) - { - return Math.Abs(_value - other.AsBaseNumericType(this.Unit)) <= maxError.AsBaseNumericType(this.Unit); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current $quantityName. - public override int GetHashCode() - { - return new { type = typeof($quantityName), Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As($unitEnumName unit) - { - if(Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this $quantityName to another $quantityName with the unit representation . - /// - /// A $quantityName with the specified unit. - public $quantityName ToUnit($unitEnumName unit) - { - var convertedValue = AsBaseNumericType(unit); - return new $quantityName(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private $baseType AsBaseUnit() - { - switch(Unit) - { -"@; foreach ($unit in $units) { - $func = $unit.FromUnitToBaseFunc.Replace("x", "_value");@" - case $unitEnumName.$($unit.SingularName): return $func; -"@; }@" - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private $baseType AsBaseNumericType($unitEnumName unit) - { - if(Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { -"@; foreach ($unit in $units) { - $func = $unit.FromBaseToUnitFunc.Replace("x", "baseUnitValue");@" - case $unitEnumName.$($unit.SingularName): return $func; -"@; }@" - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static $quantityName Parse(string str) - { - return Parse(str, null); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out $quantityName result) - { - return TryParse(str, null, out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static $unitEnumName ParseUnit(string str) - { - return ParseUnit(str, (IFormatProvider)null); - } - - #endregion - - /// - /// Set the default unit used by ToString(). Default is $baseUnitSingularName - /// - [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] - public static $unitEnumName ToStringDefaultUnit { get; set; } = $unitEnumName.$baseUnitSingularName; - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(Unit); - } - - /// - /// Get string representation of value and unit. Using current UI culture and two significant digits after radix. - /// - /// Unit representation to use. - /// String representation. - public string ToString($unitEnumName unit) - { - return ToString(unit, null, 2); - } - - /// - /// Represents the largest possible value of $quantityName - /// - public static $quantityName MaxValue => new $quantityName($baseType.MaxValue, BaseUnit); - - /// - /// Represents the smallest possible value of $quantityName - /// - public static $quantityName MinValue => new $quantityName($baseType.MinValue, BaseUnit); - - /// - /// The of this quantity. - /// - public QuantityType Type => $quantityName.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => $quantityName.BaseDimensions; - } -} -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 index 8df667a3df..d876ece7bb 100644 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 +++ b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeNetFramework.ps1 @@ -1,43 +1,35 @@ -function GenerateQuantitySourceCodeNetFramework($quantity) +using module ".\Types.psm1" + +class GeneratorArgs +{ + [Quantity]$Quantity + [Unit]$BaseUnit + [string]$UnitEnumName + [boolean]$TargetIsWindowsRuntimeComponent +} + +function GenerateQuantitySourceCodeNetFramework([Quantity]$quantity, [string]$target) { $quantityName = $quantity.Name; $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } + $valueType = $quantity.BaseType; + [Unit]$baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } | Select-Object -First 1 $baseUnitSingularName = $baseUnit.SingularName $baseUnitPluralName = $baseUnit.PluralName - $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() $unitEnumName = "$quantityName" + "Unit" + $wrc = $target -eq "WindowsRuntimeComponent" + $privateAccessModifierIfWrc = if ($wrc) { "private" } else { "public" } - # Base dimensions $baseDimensions = $quantity.BaseDimensions; - $baseDimensionLength = if($baseDimensions.L){$baseDimensions.L} else{0}; - $baseDimensionMass = if($baseDimensions.M){$baseDimensions.M} else{0}; - $baseDimensionTime = if($baseDimensions.T){$baseDimensions.T} else{0}; - $baseDimensionElectricCurrent = if($baseDimensions.I){$baseDimensions.I} else{0}; - $baseDimensionTemperature = if($baseDimensions.Θ){$baseDimensions.Θ} else{0}; - $baseDimensionAmountOfSubstance = if($baseDimensions.N){$baseDimensions.N} else{0}; - $baseDimensionLuminousIntensity = if($baseDimensions.J){$baseDimensions.J} else{0}; - - $convertToBaseType = switch ($baseType) { - "long" { "Convert.ToInt64"; break } - "double" { "Convert.ToDouble"; break } - "decimal" { "Convert.ToDecimal"; break } - default { throw "Base type not supported: $baseType" } - } - - $quantityValueType = switch ($baseType) { - "long" { "QuantityValue"; break } - "double" { "QuantityValue"; break } - "decimal" { "QuantityValue"; break } - default { throw "Base type not supported: $baseType" } - } + $isDimensionless = $baseDimensions -eq $null -or ( $baseDimensions.Length -eq 0 -and $baseDimensions.Mass -eq 0 -and $baseDimensions.Time -eq 0 -and $baseDimensions.ElectricCurrent -eq 0 -and $baseDimensions.Temperature -eq 0 -and $baseDimensions.AmountOfSubstance -eq 0 -and $baseDimensions.LuminousIntensity -eq 0 ) - $obsoleteEqualityIfDouble = '' - if ($quantity.BaseType -eq "double") { - $obsoleteEqualityIfDouble = "[Obsolete(`"It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals($quantityName, double, ComparisonType) to provide the max allowed absolute or relative error.`")]`r`n " + [GeneratorArgs]$genArgs = New-Object GeneratorArgs -Property @{ + Quantity = $quantity; + BaseUnit = $baseUnit; + UnitEnumName = $unitEnumName; + TargetIsWindowsRuntimeComponent = $wrc; } - + # $genArgs | fl | out-string | write-host -foreground yellow @" //------------------------------------------------------------------------------ // @@ -50,8 +42,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -78,156 +69,459 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; +using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { +"@; +$obsoleteAttribute = GetObsoleteAttribute($quantity); +if ($obsoleteAttribute) +{ + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this section +}@" /// - /// $($quantity.XmlDoc) + /// $($quantity.XmlDocSummary) /// - // ReSharper disable once PartialTypeWithSinglePart - - public partial struct $quantityName : IComparable, IComparable<$quantityName> +"@; if ($quantity.XmlDocRemarks) {@" + /// + /// $($quantity.XmlDocRemarks) + /// +"@; } + if($wrc) {@" + // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components + // Public structures can't have any members other than public fields, and those fields must be value types or strings. + // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. + public sealed partial class $quantityName : IQuantity +"@; } else {@" + public partial struct $quantityName : IQuantity<$unitEnumName>, IEquatable<$quantityName>, IComparable, IComparable<$quantityName> +"@; }@" { /// /// The numeric value this quantity was constructed with. /// - public $baseType Value => _value; - - #region Nullable From Methods + private readonly $valueType _value; -"@; foreach ($unit in $units) { - $valueParamName = $unit.PluralName.ToLowerInvariant();@" /// - /// Get nullable $quantityName from nullable $($unit.PluralName). + /// The unit this quantity was constructed with. /// - [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] - public static $($quantityName)? From$($unit.PluralName)($($quantityValueType)? $valueParamName) + private readonly $($unitEnumName)? _unit; + + static $quantityName() { - return $($valueParamName).HasValue ? From$($unit.PluralName)($($valueParamName).Value) : default($($quantityName)?); +"@; if($isDimensionless) + {@" + BaseDimensions = BaseDimensions.Dimensionless; +"@; } + else + {@" + BaseDimensions = new BaseDimensions($($baseDimensions.Length), $($baseDimensions.Mass), $($baseDimensions.Time), $($baseDimensions.ElectricCurrent), $($baseDimensions.Temperature), $($baseDimensions.AmountOfSubstance), $($baseDimensions.LuminousIntensity)); +"@; } +@" } - -"@; }@" +"@; # Windows Runtime Component requires a default constructor + if ($wrc) {@" /// - /// Dynamically convert from value and unit enum to . + /// Creates the quantity with a value of 0 in the base unit $baseUnitSingularName. /// - /// Value to convert from. - /// Unit to convert from. - /// $quantityName unit value. - [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] - public static $($quantityName)? From($($quantityValueType)? value, $unitEnumName fromUnit) + /// + /// Windows Runtime Component requires a default constructor. + /// + public $quantityName() { - return value.HasValue ? new $quantityName(($baseType)value.Value, fromUnit) : default($($quantityName)?); + _value = 0; + _unit = BaseUnit; } - - #endregion +"@; } @" /// - /// Get unit abbreviation string. + /// Creates the quantity with the given numeric value and unit. /// - /// Unit to get abbreviation for. - /// Format to use for localization. Defaults to . - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit, [CanBeNull] IFormatProvider provider) + /// The numeric value to contruct this quantity with. + /// The unit representation to contruct this quantity with. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. + /// If value is NaN or Infinity. + $privateAccessModifierIfWrc $quantityName($valueType numericValue, $unitEnumName unit) { - provider = provider ?? UnitSystem.DefaultCulture; + if(unit == $unitEnumName.Undefined) + throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); +"@; if ($quantity.BaseType -eq "double") {@" + _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue)); +"@; } else {@" + _value = numericValue; +"@; }@" + _unit = unit; } "@; - if ($quantity.Logarithmic -eq $true) { - # Call another script function to generate logarithm-specific arithmetic operator code. - GenerateLogarithmicArithmeticOperators -quantityName $quantityName -baseUnitFieldName $baseUnitFieldName -baseType $baseType -scalingFactor $quantity.LogarithmicScalingFactor - } - elseif ($quantity.GenerateArithmetic -eq $true) {@" + GenerateStaticProperties $genArgs + GenerateProperties $genArgs + GenerateConversionProperties $genArgs + GenerateStaticMethods $genArgs + GenerateStaticFactoryMethods $genArgs + GenerateStaticParseMethods $genArgs + GenerateArithmeticOperators $genArgs + GenerateEqualityAndComparison $genArgs + GenerateConversionMethods $genArgs +@" - #region Arithmetic Operators + #region ToString Methods - public static $quantityName operator -($quantityName right) + /// + /// Get default string representation of value and unit. + /// + /// String representation. + public override string ToString() { - return new $quantityName(-right.Value, right.Unit); + return ToString(null); } - public static $quantityName operator +($quantityName left, $quantityName right) + /// + /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// String representation. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName) { - return new $quantityName(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); - } - - public static $quantityName operator -($quantityName left, $quantityName right) + var provider = cultureName; +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider) { - return new $quantityName(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); +"@; }@" + return ToString(provider, 2); } - public static $quantityName operator *($baseType left, $quantityName right) + /// + /// Get string representation of value and unit. + /// + /// The number of significant digits after the radix point. + /// String representation. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString(string cultureName, int significantDigitsAfterRadix) { - return new $quantityName(left * right.Value, right.Unit); - } - - public static $quantityName operator *($quantityName left, $baseType right) + var provider = cultureName; +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { - return new $quantityName(left.Value * right, left.Unit); +"@; }@" + var value = Convert.ToDouble(Value); + var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); + return ToString(provider, format); } - public static $quantityName operator /($quantityName left, $baseType right) + /// + /// Get string representation of value 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. +"@; # Windows Runtime Component does not support IFormatProvider type + if ($wrc) {@" + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { - return new $quantityName(left.Value / right, left.Unit); - } - - public static double operator /($quantityName left, $quantityName right) + var provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use for localization and number formatting. Defaults to if null. + public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { - return left.$baseUnitPluralName / right.$baseUnitPluralName; +"@; }@" + if (format == null) throw new ArgumentNullException(nameof(format)); + if (args == null) throw new ArgumentNullException(nameof(args)); + + provider = provider ?? GlobalConfiguration.DefaultCulture; + + var value = Convert.ToDouble(Value); + var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); + return string.Format(provider, format, formatArgs); } #endregion -"@; }@" +"@; if ($wrc) {@" - public static bool operator <=($quantityName left, $quantityName right) + private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) { - return left.Value <= right.AsBaseNumericType(left.Unit); + return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; } +"@; } else {@" +"@; }@" + } +} +"@; +} - public static bool operator >=($quantityName left, $quantityName right) +function GenerateStaticProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitSingularName = $genArgs.BaseUnit.SingularName + $valueType = $genArgs.Quantity.BaseType +@" + + #region Static Properties + + /// + /// The of this quantity. + /// + public static BaseDimensions BaseDimensions { get; } + + /// + /// The base unit of $quantityName, which is $baseUnitSingularName. All conversions go via this value. + /// + public static $unitEnumName BaseUnit => $unitEnumName.$baseUnitSingularName; + + /// + /// Represents the largest possible value of $quantityName + /// + public static $quantityName MaxValue => new $quantityName($valueType.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of $quantityName + /// + public static $quantityName MinValue => new $quantityName($valueType.MinValue, BaseUnit); + + /// + /// The of this quantity. + /// + public static QuantityType QuantityType => QuantityType.$quantityName; + + /// + /// All units of measurement for the $quantityName quantity. + /// + public static $unitEnumName[] Units { get; } = Enum.GetValues(typeof($unitEnumName)).Cast<$unitEnumName>().Except(new $unitEnumName[]{ $unitEnumName.Undefined }).ToArray(); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit $baseUnitSingularName. + /// + public static $quantityName Zero => new $quantityName(0, BaseUnit); + + #endregion +"@; +} + +function GenerateProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitSingularName = $genArgs.BaseUnit.SingularName + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// +"@; # Windows Runtime Component does not support decimal + if ($wrc) {@" + public double Value => Convert.ToDouble(_value); +"@; } else {@" + public $valueType Value => _value; +"@; } +@" + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public $unitEnumName Unit => _unit.GetValueOrDefault(BaseUnit); + + /// + /// The of this quantity. + /// + public QuantityType Type => $quantityName.QuantityType; + + /// + /// The of this quantity. + /// + public BaseDimensions Dimensions => $quantityName.BaseDimensions; + + #endregion +"@; +} + +function GenerateConversionProperties([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $units = $genArgs.Quantity.Units +@" + + #region Conversion Properties +"@; + foreach ($unit in $units) { + $propertyName = $unit.PluralName; + $obsoleteAttribute = GetObsoleteAttribute($unit); + if ($obsoleteAttribute) + { + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page + } +@" + + /// + /// Get $quantityName in $propertyName. + /// $($obsoleteAttribute) + public double $propertyName => As($unitEnumName.$($unit.SingularName)); +"@; } +@" + + #endregion +"@; +} + +function GenerateStaticMethods([GeneratorArgs]$genArgs) +{ + $unitEnumName = $genArgs.UnitEnumName +@" + + #region Static Methods + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation($unitEnumName unit) { - return left.Value >= right.AsBaseNumericType(left.Unit); + return GetAbbreviation(unit, null); } - public static bool operator <($quantityName left, $quantityName right) + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static string GetAbbreviation($unitEnumName unit, [CanBeNull] string cultureName) { - return left.Value < right.AsBaseNumericType(left.Unit); + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use for localization. Defaults to if null. + public static string GetAbbreviation($unitEnumName unit, [CanBeNull] IFormatProvider provider) + { +"@; }@" + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } - public static bool operator >($quantityName left, $quantityName right) + #endregion +"@; +} + +function GenerateStaticFactoryMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $units = $genArgs.Quantity.Units + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Static Factory Methods + +"@; foreach ($unit in $units) { + $valueParamName = $unit.PluralName.ToLowerInvariant(); + $obsoleteAttribute = GetObsoleteAttribute($unit); + if ($obsoleteAttribute) + { + $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page + } + @" + /// + /// Get $quantityName from $($unit.PluralName). + /// $($obsoleteAttribute) + /// If value is NaN or Infinity. +"@; # Windows Runtime Component does not support overloads with same number of parameters + if ($wrc) {@" + [Windows.Foundation.Metadata.DefaultOverload] + public static $quantityName From$($unit.PluralName)(double $valueParamName) +"@; } else {@" + public static $quantityName From$($unit.PluralName)(QuantityValue $valueParamName) +"@; }@" { - return left.Value > right.AsBaseNumericType(left.Unit); + $valueType value = ($valueType) $valueParamName; + return new $quantityName(value, $unitEnumName.$($unit.SingularName)); } +"@; }@" - $($obsoleteEqualityIfDouble)public static bool operator ==($quantityName left, $quantityName right) + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// $quantityName unit value. +"@; # Windows Runtime Component does not support parameters named 'value' +if ($wrc) {@" + // Fix name conflict with parameter "value" + [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] + public static $quantityName From(double value, $unitEnumName fromUnit) +"@; } else {@" + public static $quantityName From(QuantityValue value, $unitEnumName fromUnit) +"@; }@" { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value == right.AsBaseNumericType(left.Unit); + return new $quantityName(($valueType)value, fromUnit); } - $($obsoleteEqualityIfDouble)public static bool operator !=($quantityName left, $quantityName right) + #endregion +"@; + +} + +function GenerateStaticParseMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $baseUnitPluralName = $genArgs.BaseUnit.PluralName + $units = $genArgs.Quantity.Units + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Static Parse Methods + + /// + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + /// The value of 'str' cannot be null. + /// + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// + /// + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// , and . + /// + /// + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// + public static $quantityName Parse(string str) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.Value != right.AsBaseNumericType(left.Unit); + return Parse(str, null); } - #region Parsing - /// /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -246,143 +540,454 @@ namespace UnitsNet /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static $quantityName Parse(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. public static $quantityName Parse(string str, [CanBeNull] IFormatProvider provider) { - if (str == null) throw new ArgumentNullException(nameof(str)); - - provider = provider ?? UnitSystem.DefaultCulture; +"@; }@" + return QuantityParser.Default.Parse<$quantityName, $unitEnumName>( + str, + provider, + From); + } - return QuantityParser.Parse<$quantityName, $unitEnumName>(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - $unitEnumName parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => From$baseUnitPluralName(x.$baseUnitPluralName + y.$baseUnitPluralName)); + /// + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// + /// String to parse. Typically in the form: {number} {unit} + /// Resulting unit quantity if successful. + /// + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// + public static bool TryParse([CanBeNull] string str, out $quantityName result) + { + return TryParse(str, null, out result); } /// /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// Resulting unit quantity if successful. + /// True if successful, otherwise false. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out $quantityName result) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out $quantityName result) { - provider = provider ?? UnitSystem.DefaultCulture; - - try - { - result = Parse(str, provider); - return true; - } - catch - { - result = default($quantityName); - return false; - } +"@; }@" + return QuantityParser.Default.TryParse<$quantityName, $unitEnumName>( + str, + provider, + From, + out result); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. - [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] - public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) + public static $unitEnumName ParseUnit(string str) { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); + return ParseUnit(str, null); } /// /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. public static $unitEnumName ParseUnit(string str, IFormatProvider provider = null) { - if (str == null) throw new ArgumentNullException(nameof(str)); +"@; }@" + return UnitParser.Default.Parse<$unitEnumName>(str, provider); + } - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse<$unitEnumName>(str.Trim()); + public static bool TryParseUnit(string str, out $unitEnumName unit) + { + return TryParseUnit(str, null, out unit); + } - if (unit == $unitEnumName.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized $unitEnumName."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } + /// + /// Parse a unit string. + /// + /// String to parse. Typically in the form: {number} {unit} + /// The parsed unit if successful. + /// True if successful, otherwise false. + /// + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// +"@; # Windows Runtime Component does not support IFormatProvider type +if ($wrc) {@" + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out $unitEnumName unit) + { + IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); +"@; } else {@" + /// Format to use when parsing number and unit. Defaults to if null. + public static bool TryParseUnit(string str, IFormatProvider provider, out $unitEnumName unit) + { +"@; }@" + return UnitParser.Default.TryParse<$unitEnumName>(str, provider, out unit); + } + + #endregion +"@; +} + +function GenerateLogarithmicArithmeticOperators([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $valueType = $genArgs.Quantity.BaseType + $wrc = $genArgs.TargetIsWindowsRuntimeComponent + $scalingFactor = $genArgs.Quantity.LogarithmicScalingFactor + # Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to use 20 instead. + $x = 10 * $scalingFactor; + @" + + #region Logarithmic Arithmetic Operators + + public static $quantityName operator -($quantityName right) + { + return new $quantityName(-right.Value, right.Unit); + } + + public static $quantityName operator +($quantityName left, $quantityName right) + { + // Logarithmic addition + // Formula: $x*log10(10^(x/$x) + 10^(y/$x)) + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); + } - return unit; + public static $quantityName operator -($quantityName left, $quantityName right) + { + // Logarithmic subtraction + // Formula: $x*log10(10^(x/$x) - 10^(y/$x)) + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); + } + + public static $quantityName operator *($valueType left, $quantityName right) + { + // Logarithmic multiplication = addition + return new $quantityName(left + right.Value, right.Unit); + } + + public static $quantityName operator *($quantityName left, double right) + { + // Logarithmic multiplication = addition + return new $quantityName(left.Value + ($valueType)right, left.Unit); + } + + public static $quantityName operator /($quantityName left, double right) + { + // Logarithmic division = subtraction + return new $quantityName(left.Value - ($valueType)right, left.Unit); + } + + public static double operator /($quantityName left, $quantityName right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); } #endregion +"@; +} - #region ToString Methods +function GenerateArithmeticOperators([GeneratorArgs]$genArgs) +{ + # Windows Runtime Component does not support operator overloads + if ($wrc -or (-not $quantity.GenerateArithmetic)) { return } + + # Logarithmic units required different arithmetic + if ($quantity.Logarithmic) { + GenerateLogarithmicArithmeticOperators $genArgs + return + } + + $quantityName = $genArgs.Quantity.Name + $baseUnitPluralName = $genArgs.BaseUnit.PluralName + $valueType = $genArgs.Quantity.BaseType + @" + + #region Arithmetic Operators + + public static $quantityName operator -($quantityName right) + { + return new $quantityName(-right.Value, right.Unit); + } + + public static $quantityName operator +($quantityName left, $quantityName right) + { + return new $quantityName(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static $quantityName operator -($quantityName left, $quantityName right) + { + return new $quantityName(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); + } + + public static $quantityName operator *($valueType left, $quantityName right) + { + return new $quantityName(left * right.Value, right.Unit); + } + + public static $quantityName operator *($quantityName left, $valueType right) + { + return new $quantityName(left.Value * right, left.Unit); + } + + public static $quantityName operator /($quantityName left, $valueType right) + { + return new $quantityName(left.Value / right, left.Unit); + } + + public static double operator /($quantityName left, $quantityName right) + { + return left.$baseUnitPluralName / right.$baseUnitPluralName; + } + + #endregion +"@; +} + +function GenerateEqualityAndComparison([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $wrc = $genArgs.TargetIsWindowsRuntimeComponent +@" + + #region Equality / IComparable + +"@; # Windows Runtime Component does not support operator overloads + if (-not $wrc) {@" + public static bool operator <=($quantityName left, $quantityName right) + { + return left.Value <= right.AsBaseNumericType(left.Unit); + } + + public static bool operator >=($quantityName left, $quantityName right) + { + return left.Value >= right.AsBaseNumericType(left.Unit); + } + + public static bool operator <($quantityName left, $quantityName right) + { + return left.Value < right.AsBaseNumericType(left.Unit); + } + + public static bool operator >($quantityName left, $quantityName right) + { + return left.Value > right.AsBaseNumericType(left.Unit); + } + + public static bool operator ==($quantityName left, $quantityName right) + { + return left.Equals(right); + } + + public static bool operator !=($quantityName left, $quantityName right) + { + return !(left == right); + } + +"@; }@" + public int CompareTo(object obj) + { + if(obj is null) throw new ArgumentNullException(nameof(obj)); + if(!(obj is $quantityName obj$quantityName)) throw new ArgumentException("Expected type $quantityName.", nameof(obj)); + + return CompareTo(obj$quantityName); + } + +"@; # Windows Runtime Component does not support overloads with same number of parameters +$accessModifier = if ($wrc) { "internal" } else { "public" } @" + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + $accessModifier int CompareTo($quantityName other) + { + return _value.CompareTo(other.AsBaseNumericType(this.Unit)); + } + +"@; + if ($wrc) {@" + [Windows.Foundation.Metadata.DefaultOverload] +"@; }@" + public override bool Equals(object obj) + { + if(obj is null || !(obj is $quantityName obj$quantityName)) + return false; + + return Equals(obj$quantityName); + } + + public bool Equals($quantityName other) + { + return _value.Equals(other.AsBaseNumericType(this.Unit)); + } /// - /// Get string representation of value and unit. Using two significant digits after radix. + /// + /// Compare equality to another $quantityName within the given absolute or relative tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a percentage of this quantity's value. will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// as a fixed number in this quantity's unit. will be converted into + /// this quantity's unit for comparison. + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating point operations and using System.Double internally. + /// /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . - /// String representation. - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider) + /// The other quantity to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// The comparison type: either relative or absolute. + /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. + public bool Equals($quantityName other, double tolerance, ComparisonType comparisonType) { - return ToString(unit, provider, 2); + if(tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = (double)this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// - /// Get string representation of value and unit. + /// Returns the hash code for this instance. /// - /// Unit representation to use. - /// Format to use for localization and number formatting. Defaults to . - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) + /// A hash code for the current $quantityName. + public override int GetHashCode() { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, provider, format); + return new { QuantityType, Value, Unit }.GetHashCode(); } + #endregion +"@; +} + +function GenerateConversionMethods([GeneratorArgs]$genArgs) +{ + $quantityName = $genArgs.Quantity.Name + $unitEnumName = $genArgs.UnitEnumName + $valueType = $genArgs.Quantity.BaseType +@" + + #region Conversion Methods + /// - /// Get string representation of value and unit. + /// Convert to the unit representation . /// - /// Format to use for localization and number formatting. Defaults to . - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) + /// Value converted to the specified unit. + public double As($unitEnumName unit) { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); + if(Unit == unit) + return Convert.ToDouble(Value); - provider = provider ?? UnitSystem.DefaultCulture; + var converted = AsBaseNumericType(unit); + return Convert.ToDouble(converted); + } - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); + /// + /// Converts this $quantityName to another $quantityName with the unit representation . + /// + /// A $quantityName with the specified unit. + public $quantityName ToUnit($unitEnumName unit) + { + var convertedValue = AsBaseNumericType(unit); + return new $quantityName(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private $valueType AsBaseUnit() + { + switch(Unit) + { +"@; foreach ($unit in $units) { + $func = $unit.FromUnitToBaseFunc.Replace("x", "_value");@" + case $unitEnumName.$($unit.SingularName): return $func; +"@; }@" + default: + throw new NotImplementedException($"Can not convert {Unit} to base units."); + } + } + + private $valueType AsBaseNumericType($unitEnumName unit) + { + if(Unit == unit) + return _value; + + var baseUnitValue = AsBaseUnit(); + + switch(unit) + { +"@; foreach ($unit in $units) { + $func = $unit.FromBaseToUnitFunc.Replace("x", "baseUnitValue");@" + case $unitEnumName.$($unit.SingularName): return $func; +"@; }@" + default: + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } } #endregion - } -} "@; } diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 deleted file mode 100644 index 59b33e8fa2..0000000000 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCodeWindowsRuntimeComponent.ps1 +++ /dev/null @@ -1,297 +0,0 @@ -function GenerateQuantitySourceCodeWindowsRuntimeComponent($quantity) -{ - $quantityName = $quantity.Name; - $units = $quantity.Units; - $baseType = $quantity.BaseType; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } - $baseUnitSingularName = $baseUnit.SingularName - $baseUnitPluralName = $baseUnit.PluralName - $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() - $unitEnumName = "$quantityName" + "Unit" - - # Base dimensions - $baseDimensions = $quantity.BaseDimensions; - $baseDimensionLength = if($baseDimensions.L){$baseDimensions.L} else{0}; - $baseDimensionMass = if($baseDimensions.M){$baseDimensions.M} else{0}; - $baseDimensionTime = if($baseDimensions.T){$baseDimensions.T} else{0}; - $baseDimensionElectricCurrent = if($baseDimensions.I){$baseDimensions.I} else{0}; - $baseDimensionTemperature = if($baseDimensions.Θ){$baseDimensions.Θ} else{0}; - $baseDimensionAmountOfSubstance = if($baseDimensions.N){$baseDimensions.N} else{0}; - $baseDimensionLuminousIntensity = if($baseDimensions.J){$baseDimensions.J} else{0}; - - $convertToBaseType = switch ($baseType) { - "long" { "Convert.ToInt64"; break } - "double" { "Convert.ToDouble"; break } - "decimal" { "Convert.ToDecimal"; break } - default { throw "Base type not supported: $baseType" } - } - - $quantityValueType = switch ($baseType) { - "long" { "QuantityValue"; break } - "double" { "QuantityValue"; break } - "decimal" { "QuantityValue"; break } - default { throw "Base type not supported: $baseType" } - } - - $obsoleteEqualityIfDouble = '' - if ($quantity.BaseType -eq "double") { - $obsoleteEqualityIfDouble = "[Obsolete(`"It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals($quantityName, double, ComparisonType) to provide the max allowed absolute or relative error.`")]`r`n " - } - -@" -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// $($quantity.XmlDoc) - /// - // ReSharper disable once PartialTypeWithSinglePart - - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class $quantityName - { - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - /// Creates the quantity with a value of 0 in the base unit $baseUnitSingularName. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public $quantityName() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. - /// Unit abbreviation string. - [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit, [CanBeNull] string cultureName) - { - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); - } - - #region Parsing - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static $quantityName Parse(string str, [CanBeNull] string cultureName) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - return QuantityParser.Parse<$quantityName, $unitEnumName>(str, provider, - delegate(string value, string unit, IFormatProvider formatProvider2) - { - double parsedValue = double.Parse(value, formatProvider2); - $unitEnumName parsedUnit = ParseUnit(unit, formatProvider2); - return From(parsedValue, parsedUnit); - }, (x, y) => From$baseUnitPluralName(x.$baseUnitPluralName + y.$baseUnitPluralName)); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out $quantityName result) - { - try - { - result = Parse(str, cultureName); - return true; - } - catch - { - result = default($quantityName); - return false; - } - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) - { - return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to . - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - internal static $unitEnumName ParseUnit(string str, IFormatProvider provider = null) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - var unitSystem = UnitSystem.GetCached(provider); - var unit = unitSystem.Parse<$unitEnumName>(str.Trim()); - - if (unit == $unitEnumName.Undefined) - { - var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized $unitEnumName."); - newEx.Data["input"] = str; - newEx.Data["provider"] = provider?.ToString() ?? "(null)"; - throw newEx; - } - - return unit; - } - - #endregion - - #region ToString Methods - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// String representation. - public string ToString($unitEnumName unit, [CanBeNull] string cultureName) - { - return ToString(unit, cultureName, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// Unit representation to use. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// The number of significant digits after the radix point. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix) - { - double value = As(unit); - string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, cultureName, format); - } - - /// - /// Get string representation of value and unit. - /// - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. - /// Unit representation to use. - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx - IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); - - double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - } -} -"@; -} diff --git a/UnitsNet/Scripts/Include-GenerateQuantityTypeSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateQuantityTypeSourceCode.ps1 index 3fd76fd4dd..a480e56f37 100644 --- a/UnitsNet/Scripts/Include-GenerateQuantityTypeSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateQuantityTypeSourceCode.ps1 @@ -12,25 +12,24 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/UnitsNet/Scripts/Include-GenerateTemplates.ps1 b/UnitsNet/Scripts/Include-GenerateTemplates.ps1 index 915c6b2ebb..f6b2d15ce7 100644 --- a/UnitsNet/Scripts/Include-GenerateTemplates.ps1 +++ b/UnitsNet/Scripts/Include-GenerateTemplates.ps1 @@ -3,11 +3,11 @@ Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats #> -function GetObsoleteAttribute($quantity) +function GetObsoleteAttribute($quantityOrUnit) { - if ($quantity.ObsoleteText) + if ($quantityOrUnit.ObsoleteText) { - return "[System.Obsolete(""$($quantity.ObsoleteText)"")]"; + return "[System.Obsolete(""$($quantityOrUnit.ObsoleteText)"")]"; } return ""; -} \ No newline at end of file +} diff --git a/UnitsNet/Scripts/Include-GenerateUnitSystemDefaultSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateUnitSystemDefaultSourceCode.ps1 index b8ca8382e2..70f5fb2d82 100644 --- a/UnitsNet/Scripts/Include-GenerateUnitSystemDefaultSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateUnitSystemDefaultSourceCode.ps1 @@ -1,4 +1,4 @@ -function GenerateUnitSystemDefaultSourceCode($quantities) +function GenerateUnitSystemDefaultSourceCode($quantities) { @" //------------------------------------------------------------------------------ @@ -12,25 +12,24 @@ function GenerateUnitSystemDefaultSourceCode($quantities) // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,9 +38,7 @@ function GenerateUnitSystemDefaultSourceCode($quantities) // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System.Collections.Generic; -using System.Collections.ObjectModel; -using UnitsNet.I18n; +using System; using UnitsNet.Units; // ReSharper disable RedundantCommaInArrayInitializer @@ -49,48 +46,34 @@ using UnitsNet.Units; namespace UnitsNet { - public sealed partial class UnitSystem + public partial class UnitAbbreviationsCache { - private static readonly ReadOnlyCollection DefaultLocalizations - = new ReadOnlyCollection(new List + private static readonly (string CultureName, Type UnitType, int UnitValue, string[] UnitAbbreviations)[] GeneratedLocalizations + = new [] { "@; - foreach ($quantity in $quantities) + foreach ($quantity in $quantities) { $quantityName = $quantity.Name; $unitEnumName = "$quantityName" + "Unit"; -@" - new UnitLocalization(typeof ($unitEnumName), - new[] - { -"@; - foreach ($unit in $quantity.Units) + + foreach ($unit in $quantity.Units) { $enumValue = $unit.SingularName; -@" - new CulturesForEnumValue((int) $unitEnumName.$enumValue, - new[] - { -"@; - foreach ($localization in $unit.Localization) + + foreach ($localization in $unit.Localization) { $cultureName = $localization.Culture; $abbreviationParams = $localization.Abbreviations -join '", "' @" - new AbbreviationsForCulture("$cultureName", "$abbreviationParams"), + (`"$cultureName`", typeof($unitEnumName), (int)$unitEnumName.$enumValue, new string[]{`"$abbreviationParams`"}), "@; } -@" - }), -"@; } -@" - }), -"@; } @" - }); + }; } } "@; -} \ No newline at end of file +} diff --git a/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 index 37e87d401d..2529555d72 100644 --- a/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateUnitTestBaseClassSourceCode.ps1 @@ -1,12 +1,14 @@ -function GenerateUnitTestBaseClassSourceCode($quantity) +using module ".\Types.psm1" +function GenerateUnitTestBaseClassSourceCode([Quantity]$quantity) { - $quantityName = $quantity.Name; - $baseType = $quantity.BaseType; - $units = $quantity.Units; - $baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } + $quantityName = $quantity.Name + $units = $quantity.Units + $valueType = $quantity.BaseType + [Unit]$baseUnit = $units | where { $_.SingularName -eq $quantity.BaseUnit } | Select-Object -First 1 + $baseUnitSingularName = $baseUnit.SingularName $baseUnitPluralName = $baseUnit.PluralName - $baseUnitVariableName = $baseUnit.SingularName.ToLowerInvariant(); - $unitEnumName = "$($quantityName)Unit"; + $baseUnitVariableName = $baseUnitSingularName.ToLowerInvariant() + $unitEnumName = "$quantityName" + "Unit" @" //------------------------------------------------------------------------------ @@ -20,8 +22,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ @@ -74,6 +75,27 @@ namespace UnitsNet.Tests "@; }@" // ReSharper restore VirtualMemberNeverOverriden.Global + [Fact] + public void Ctor_WithUndefinedUnit_ThrowsArgumentException() + { + Assert.Throws(() => new $quantityName(($valueType)0.0, $unitEnumName.Undefined)); + } + +"@; if ($quantity.BaseType -eq "double") {@" + [Fact] + public void Ctor_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => new $quantityName(double.PositiveInfinity, $unitEnumName.$($baseUnit.SingularName))); + Assert.Throws(() => new $quantityName(double.NegativeInfinity, $unitEnumName.$($baseUnit.SingularName))); + } + + [Fact] + public void Ctor_WithNaNValue_ThrowsArgumentException() + { + Assert.Throws(() => new $quantityName(double.NaN, $unitEnumName.$($baseUnit.SingularName))); + } +"@; }@" + [Fact] public void $($baseUnit.SingularName)To$($quantityName)Units() { @@ -91,6 +113,21 @@ namespace UnitsNet.Tests "@; }@" } +"@; if ($quantity.BaseType -eq "double") {@" + [Fact] + public void From$($baseUnit.PluralName)_WithInfinityValue_ThrowsArgumentException() + { + Assert.Throws(() => $quantityName.From$($baseUnit.PluralName)(double.PositiveInfinity)); + Assert.Throws(() => $quantityName.From$($baseUnit.PluralName)(double.NegativeInfinity)); + } + + [Fact] + public void From$($baseUnit.PluralName)_WithNanValue_ThrowsArgumentException() + { + Assert.Throws(() => $quantityName.From$($baseUnit.PluralName)(double.NaN)); + } +"@; }@" + [Fact] public void As() { @@ -198,28 +235,43 @@ namespace UnitsNet.Tests Assert.Throws(() => $baseUnitVariableName.CompareTo(null)); } - [Fact] public void EqualityOperators() { - $quantityName a = $quantityName.From$baseUnitPluralName(1); - $quantityName b = $quantityName.From$baseUnitPluralName(2); + var a = $quantityName.From$baseUnitPluralName(1); + var b = $quantityName.From$baseUnitPluralName(2); + + // ReSharper disable EqualExpressionComparison -// ReSharper disable EqualExpressionComparison Assert.True(a == a); - Assert.True(a != b); + Assert.False(a != a); + Assert.True(a != b); Assert.False(a == b); - Assert.False(a != a); + + Assert.False(a == null); + Assert.False(null == a); + // ReSharper restore EqualExpressionComparison } [Fact] public void EqualsIsImplemented() { - $quantityName v = $quantityName.From$baseUnitPluralName(1); - Assert.True(v.Equals($quantityName.From$baseUnitPluralName(1), $quantityName.From$baseUnitPluralName($($baseUnitPluralName)Tolerance))); - Assert.False(v.Equals($quantityName.Zero, $quantityName.From$baseUnitPluralName($($baseUnitPluralName)Tolerance))); + var a = $quantityName.From$baseUnitPluralName(1); + var b = $quantityName.From$baseUnitPluralName(2); + + Assert.True(a.Equals(a)); + Assert.False(a.Equals(b)); + Assert.False(a.Equals(null)); + } + + [Fact] + public void EqualsRelativeToleranceIsImplemented() + { + var v = $quantityName.From$baseUnitPluralName(1); + Assert.True(v.Equals($quantityName.From$baseUnitPluralName(1), $($baseUnitPluralName)Tolerance, ComparisonType.Relative)); + Assert.False(v.Equals($quantityName.Zero, $($baseUnitPluralName)Tolerance, ComparisonType.Relative)); } [Fact] @@ -242,6 +294,24 @@ namespace UnitsNet.Tests Assert.DoesNotContain($unitEnumName.Undefined, $quantityName.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); + } + } + + [Fact] + public void BaseDimensionsShouldNeverBeNull() + { + Assert.False($quantityName.BaseDimensions is null); + } } } "@; diff --git a/UnitsNet/Scripts/Include-GenerateUnitTestPlaceholderSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateUnitTestPlaceholderSourceCode.ps1 index a2fe7a0239..870714e402 100644 --- a/UnitsNet/Scripts/Include-GenerateUnitTestPlaceholderSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateUnitTestPlaceholderSourceCode.ps1 @@ -5,9 +5,9 @@ function GenerateUnitTestPlaceholderSourceCode($quantity) //------------------------------------------------------------------------------ // // This code was generated (once) by \generate-code.bat, but will not be -// regenerated when it already exists. The purpose of creating this file is to make +// regenerated when it already exists. The purpose of creating this file is to make // it easier to remember to implement all the unit conversion test cases. -// +// // Whenever a new unit is added to this quantity and \generate-code.bat is run, // the base test class will get a new abstract property and cause a compile error // in this derived class, reminding the developer to implement the test case @@ -16,25 +16,24 @@ function GenerateUnitTestPlaceholderSourceCode($quantity) // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -50,7 +49,7 @@ namespace UnitsNet.Tests.CustomCode { public class $($quantityName)Tests : $($quantityName)TestsBase { - // TODO Override properties in base class here + // Override properties in base class here } } "@; diff --git a/UnitsNet/Scripts/Include-GenerateUnitTypeSourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateUnitTypeSourceCode.ps1 index 9459d05e78..548b03b6f6 100644 --- a/UnitsNet/Scripts/Include-GenerateUnitTypeSourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateUnitTypeSourceCode.ps1 @@ -14,8 +14,7 @@ // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. -// Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // //------------------------------------------------------------------------------ diff --git a/UnitsNet/Scripts/Types.psm1 b/UnitsNet/Scripts/Types.psm1 new file mode 100644 index 0000000000..11151b0bd2 --- /dev/null +++ b/UnitsNet/Scripts/Types.psm1 @@ -0,0 +1,43 @@ +class Quantity +{ + [string]$Name + [string]$XmlDocSummary + [string]$XmlDocRemarks + [string]$BaseUnit + [string]$BaseType # TODO Rename me to ValueType + [BaseDimensions]$BaseDimensions = [BaseDimensions]::new() + [boolean]$GenerateArithmetic = $true + [boolean]$Logarithmic = $false + [int]$LogarithmicScalingFactor = 1 + [Unit[]]$Units = @() +} + +class Unit +{ + [string]$SingularName + [string]$PluralName + [string]$XmlDocSummary + [string]$XmlDocRemarks + [string]$FromUnitToBaseFunc + [string]$FromBaseToUnitFunc + [string[]]$Prefixes = @() + [Localization[]]$Localization = @() +} + +class Localization +{ + [string]$Culture + [string[]]$Abbreviations = @() + [string[]]$AbbreviationsWithPrefixes = @() +} + +class BaseDimensions +{ + [int]$Length = 0 + [int]$Mass = 0 + [int]$Time = 0 + [int]$ElectricCurrent = 0 + [int]$Temperature = 0 + [int]$AmountOfSubstance = 0 + [int]$LuminousIntensity = 0 +} diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index 632e8c6374..cf5ac3a15a 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -1,16 +1,16 @@ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,6 +20,7 @@ // THE SOFTWARE. using System; +using System.Globalization; using System.Linq; using System.Reflection; using UnitsNet.InternalHelpers; @@ -69,23 +70,38 @@ public static class UnitConverter /// /// 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 abbrevation. public static double ConvertByName(FromValue fromValue, string quantityName, string fromUnit, string toUnit) { - Type quantityType = GetQuantityType(quantityName); - Type unitType = GetUnitType(quantityName); + if(!TryGetQuantityType(quantityName, out var quantityType)) + throw new QuantityNotFoundException($"The given quantity name was not found: {quantityName}"); - object fromUnitValue = ParseUnit(unitType, fromUnit); // ex: LengthUnit.Meter - object toUnitValue = ParseUnit(unitType, toUnit); // ex: LengthUnit.Centimeter + if(!TryGetUnitType(quantityName, out var unitType)) + throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); - MethodInfo fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) - object fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) + if(!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter + { + var e = new UnitNotFoundException($"Unit not found [{fromUnit}]."); + e.Data["unitName"] = fromUnit; + throw e; + } + + if(!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter + { + var e = new UnitNotFoundException($"Unit not found [{toUnit}]."); + e.Data["unitName"] = toUnit; + throw e; + } + + var fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) + var fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) - MethodInfo asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) - object asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) + var asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) + var asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) - return (double) asResult; + return (double)asResult; } /// @@ -117,18 +133,28 @@ public static double ConvertByName(FromValue fromValue, string quantityName, str /// True if conversion was successful. public static bool TryConvertByName(FromValue inputValue, string quantityName, string fromUnit, string toUnit, out double result) { - try - { - // TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating - // https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx - result = ConvertByName(inputValue, quantityName, fromUnit, toUnit); - return true; - } - catch - { - result = 0; + result = 0d; + + if(!TryGetQuantityType(quantityName, out var quantityType)) return false; - } + + 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; + + var fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) + var fromResult = fromMethod.Invoke(null, new[] {inputValue, 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[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) + + result = (double)asResult; + return true; } /// @@ -196,20 +222,24 @@ public static double ConvertByAbbreviation(FromValue fromValue, string quantityN /// More than one unit matches the abbrevation. public static double ConvertByAbbreviation(FromValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string culture) { - Type quantityType = GetQuantityType(quantityName); - Type unitType = GetUnitType(quantityName); + 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}"); - UnitSystem unitSystem = UnitSystem.GetCached(culture); - object fromUnitValue = unitSystem.Parse(fromUnitAbbrev, unitType); // ex: ("m", LengthUnit) => LengthUnit.Meter - object toUnitValue = unitSystem.Parse(toUnitAbbrev, unitType); // ex:("cm", LengthUnit) => LengthUnit.Centimeter + var cultureInfo = string.IsNullOrWhiteSpace(culture)? GlobalConfiguration.DefaultCulture : new CultureInfo(culture); - MethodInfo fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) - object fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) + 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 - MethodInfo asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) - object asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) + var fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) + var fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) - return (double) asResult; + var asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) + var asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) + + return (double)asResult; } /// @@ -275,20 +305,31 @@ public static bool TryConvertByAbbreviation(FromValue fromValue, string quantity public static bool TryConvertByAbbreviation(FromValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, string culture) { - try - { - // TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating - // https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx - result = ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, culture); - return true; - } - catch - { - result = 0; + 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[] {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[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) + + result = (double)asResult; + return true; + } private static MethodInfo GetAsMethod(Type quantityType, Type unitType) { @@ -316,14 +357,14 @@ private static MethodInfo GetStaticFromMethod(Type quantityType, Type unitType) private static bool HasParameterTypes(MethodInfo methodInfo, params Type[] expectedTypes) { - ParameterInfo[] parameters = methodInfo.GetParameters(); + 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++) { - ParameterInfo p = parameters[i]; - Type t = expectedTypes[i]; + var p = parameters[i]; + var t = expectedTypes[i]; if (p.ParameterType != t) return false; } @@ -337,40 +378,43 @@ private static bool HasParameterTypes(MethodInfo methodInfo, params Type[] expec /// /// Unit type, such as . /// Unit name, such as "Meter" corresponding to . - /// Unit enum value, such as boxed as an object. + /// The return enum value, such as boxed as an object. + /// True if succeeded, otherwise false. /// No unit values match the . - private static object ParseUnit(Type unitType, string unitName) + private static bool TryParseUnit(Type unitType, string unitName, out object unitValue) { - object unitValue; // ex: LengthUnit.Meter - try - { - unitValue = Enum.Parse(unitType, unitName); - } - catch (Exception e) - { - var e2 = new UnitNotFoundException($"Unit not found [{unitName}].", e); - e2.Data["unitName"] = unitName; - throw e2; - } - return unitValue; + unitValue = null; + + if(!Enum.IsDefined(unitType, unitName)) + return false; + + unitValue = Enum.Parse(unitType, unitName); + if(unitValue == null) + return false; + + return true; } - private static Type GetUnitType(string quantityName) + private static bool TryGetUnitType(string quantityName, out Type unitType) { string unitTypeName = $"{UnitTypeNamespace}.{quantityName}Unit"; - Type unitType = UnitsNetAssembly.GetType(unitTypeName); // ex: UnitsNet.Units.LengthUnit enum - if (unitType == null) - throw new UnitNotFoundException($"Unit type name not found: {unitTypeName}"); - return unitType; + + unitType = UnitsNetAssembly.GetType(unitTypeName); // ex: UnitsNet.Units.LengthUnit enum + if(unitType == null) + return false; + + return true; } - private static Type GetQuantityType(string quantityName) + private static bool TryGetQuantityType(string quantityName, out Type quantityType) { string quantityTypeName = $"{QuantityNamespace}.{quantityName}"; - Type quantityType = UnitsNetAssembly.GetType(quantityTypeName); // ex: UnitsNet.Length struct - if (quantityType == null) - throw new QuantityNotFoundException($"Quantity type name not found: {quantityTypeName}"); - return quantityType; + + quantityType = UnitsNetAssembly.GetType(quantityTypeName); // ex: UnitsNet.Length struct + if(quantityType == null) + return false; + + return true; } } -} \ No newline at end of file +} diff --git a/UnitsNet/UnitFormatter.cs b/UnitsNet/UnitFormatter.cs index ef1cfbfc5f..a60e1ac65c 100644 --- a/UnitsNet/UnitFormatter.cs +++ b/UnitsNet/UnitFormatter.cs @@ -90,10 +90,10 @@ private static bool NearlyEqual(double a, double b) /// 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 : struct, IComparable, IFormattable + where TUnitType : Enum { - string abbreviation = UnitSystem.GetCached(culture).GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit)); + string abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); return new object[] {value, abbreviation}.Concat(args).ToArray(); } } -} \ No newline at end of file +} diff --git a/UnitsNet/UnitSystem.cs b/UnitsNet/UnitSystem.cs new file mode 100644 index 0000000000..695626b763 --- /dev/null +++ b/UnitsNet/UnitSystem.cs @@ -0,0 +1,125 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Text; +using UnitsNet.Units; + +namespace UnitsNet +{ +#if !WINDOWS_UWP + public sealed partial class UnitSystem : IEquatable { } +#endif + + public sealed partial 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); + } + +#if WINDOWS_UWP + [Windows.Foundation.Metadata.DefaultOverload] +#endif + public bool Equals(UnitSystem other) + { + if(other is null) + return false; + + return BaseUnits.Equals(other.BaseUnits); + } + +#if !WINDOWS_UWP + + /// + /// Checks if this instance is equal to another. + /// + /// The left instance. + /// The right instance. + /// True if equal, otherwise false. + /// + public static bool operator ==(UnitSystem left, UnitSystem right) + { + return left is null ? right is null : left.Equals(right); + } + + /// + /// Checks if this instance is equal to another. + /// + /// The left instance. + /// The right instance. + /// True if equal, otherwise false. + /// + public static bool operator !=(UnitSystem left, UnitSystem right) + { + return !(left == right); + } + +#endif + + /// + 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/UnitsNet.Common.props b/UnitsNet/UnitsNet.Common.props deleted file mode 100644 index 4f6f89365b..0000000000 --- a/UnitsNet/UnitsNet.Common.props +++ /dev/null @@ -1,49 +0,0 @@ - - - - UnitsNet - 3.111.0 - Andreas Gullberg Larsen - Units.NET - Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. - Copyright (c) 2013 Andreas Gullberg Larsen - true - true - true - https://github.com/angularsen/UnitsNet - https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png - https://github.com/angularsen/UnitsNet - https://github.com/angularsen/UnitsNet/blob/master/LICENSE - false - unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable - - - - - netstandard1.0;net35;net40 - UnitsNet - - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client - CS1701;CS1702;CS1705;CS0618;CS0809;CS1591 - - - - - - - - - - - Common\%(RecursiveDir)%(Filename)%(Extension) - - - Common\%(RecursiveDir)%(Filename)%(Extension) - - - - - - - - diff --git a/UnitsNet/UnitsNet.Signed.csproj b/UnitsNet/UnitsNet.Signed.csproj deleted file mode 100644 index df838a9ab5..0000000000 --- a/UnitsNet/UnitsNet.Signed.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - UnitsNet.Signed - Units.NET (signed) - DEPRECATED - DEPRECATED! Use UnitsNet 4.0.0 or later instead, which is now signed. This package will be unlisted sometime later. Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. - - - - - SIGNED - true - $(MSBuildProjectDirectory)\..\UnitsNet.snk - - - diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index ed28e5fbcf..d1fe305e5f 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -1,3 +1,57 @@ - - + + + + UnitsNet + 4.0.0-beta2 + Andreas Gullberg Larsen + Units.NET + Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. + Copyright (c) 2013 Andreas Gullberg Larsen + true + https://github.com/angularsen/UnitsNet + https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png + https://github.com/angularsen/UnitsNet + https://github.com/angularsen/UnitsNet/blob/master/LICENSE + false + unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable + + + + + 4.0.0.0 + 7.3 + CS1701;CS1702;CS1705;CS0618;CS0809;CS1591 + UnitsNet + netstandard2.0;net40 + + + + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + + + + + ../UnitsNet.snk + false + true + + + + + + + + + + + + + Common\%(RecursiveDir)%(Filename)%(Extension) + + + + diff --git a/UnitsNet/Vector2.cs b/UnitsNet/Vector2.cs deleted file mode 100644 index c9aa4617c3..0000000000 --- a/UnitsNet/Vector2.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; - -namespace UnitsNet -{ -#if WINDOWS_UWP - public struct Vector2 - { - public double X; - public double Y; - } -#else - public struct Vector2 : IEquatable - { - public readonly double X; - public readonly double Y; - - public Vector2(double x, double y) - { - X = x; - Y = y; - } - - public Vector2(double xy) : this() - { - X = xy; - Y = xy; - } - - #region Equality - - private static IEqualityComparer XyComparer { get; } = new XyEqualityComparer(); - - public bool Equals(Vector2 other) - { - return XyComparer.Equals(this, other); - } - - public static bool operator !=(Vector2 left, Vector2 right) - { - return !XyComparer.Equals(left, right); - } - - public static bool operator ==(Vector2 left, Vector2 right) - { - return XyComparer.Equals(left, right); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is Vector2 && Equals((Vector2) obj); - } - - public override int GetHashCode() - { - unchecked - { - return (X.GetHashCode()*397) ^ Y.GetHashCode(); - } - } - - private sealed class XyEqualityComparer : IEqualityComparer - { - public bool Equals(Vector2 x, Vector2 y) - { - return x.X.Equals(y.X) && x.Y.Equals(y.Y); - } - - public int GetHashCode(Vector2 obj) - { - unchecked - { - return (obj.X.GetHashCode()*397) ^ obj.Y.GetHashCode(); - } - } - } - - #endregion - - public override string ToString() - { - return $"[{X:0.####}, {Y:0.####}]"; - } - } -#endif -} \ No newline at end of file diff --git a/UnitsNet/Vector3.cs b/UnitsNet/Vector3.cs deleted file mode 100644 index 9917984426..0000000000 --- a/UnitsNet/Vector3.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). -// https://github.com/angularsen/UnitsNet -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; - -namespace UnitsNet -{ -#if WINDOWS_UWP - public struct Vector3 - { - public double X; - public double Y; - public double Z; - } -#else - public struct Vector3 : IEquatable - { - public readonly double X; - public readonly double Y; - public readonly double Z; - - public Vector3(double x, double y, double z) - { - X = x; - Y = y; - Z = z; - } - - #region Equality - - public Vector3(double xyz) : this() - { - X = xyz; - Y = xyz; - Z = xyz; - } - - private static IEqualityComparer XyzComparer { get; } = new XyzEqualityComparer(); - - public bool Equals(Vector3 other) - { - return XyzComparer.Equals(this, other); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is Vector3 && Equals((Vector3) obj); - } - - public override int GetHashCode() - { - unchecked - { - int hashCode = X.GetHashCode(); - hashCode = (hashCode*397) ^ Y.GetHashCode(); - hashCode = (hashCode*397) ^ Z.GetHashCode(); - return hashCode; - } - } - - private sealed class XyzEqualityComparer : IEqualityComparer - { - public bool Equals(Vector3 x, Vector3 y) - { - return x.X.Equals(y.X) && x.Y.Equals(y.Y) && x.Z.Equals(y.Z); - } - - public int GetHashCode(Vector3 obj) - { - unchecked - { - int hashCode = obj.X.GetHashCode(); - hashCode = (hashCode*397) ^ obj.Y.GetHashCode(); - hashCode = (hashCode*397) ^ obj.Z.GetHashCode(); - return hashCode; - } - } - } - - #endregion - - public override string ToString() - { - return $"[{X:0.####}, {Y:0.####}, {Z:0.####}]"; - } - } -#endif -} \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 9c0b403bd4..06eaf58c3f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,17 +1,19 @@ version: '{build}' image: Visual Studio 2017 -only_commits: - files: - - appveyor.yml - - '**/*.sln' - - '**/*.csproj' - - '**/*.props' - - '**/*.nuspec' - - '**/*.cs' - - '**/*.json' - - '**/*.ps1' - - '**/*.psm1' - - '**/*.bat' +skip_commits: + files: + - docs/* + - '**/*.md' + +# Only fetch the latest commits to reduce time to download on agent, but support pushes containing multiple commits +clone_depth: 50 + +# build cache to preserve files/folders between builds +cache: + - packages -> **\packages.config # preserve "packages" directory in the root of build folder but will reset it if packages.config is modified + - '%LocalAppData%\NuGet\Cache' # NuGet < v3 + - '%LocalAppData%\NuGet\v3-cache' # NuGet v3 + build_script: - ps: | ##################################### @@ -37,20 +39,24 @@ build_script: Write-Host "Build failed with exit code $BuildExitCode." exit $BuildExitCode } + # Do not build feature branch with open Pull Requests skip_branch_with_pr: true test: off + artifacts: - path: Artifacts\UnitsNet.zip - path: 'Artifacts\NuGet\*.nupkg' # find all NuGet packages recursively -environment: - api_key: - secure: NlJ+D6kXfgU6RgRuf9okylLDENp8DA3tTRSC6UHBNbRS9ZAvRrC3Z0++Mr5VtGvz + deploy: - provider: NuGet api_key: secure: NlJ+D6kXfgU6RgRuf9okylLDENp8DA3tTRSC6UHBNbRS9ZAvRrC3Z0++Mr5VtGvz - skip_symbols: false on: branch: master +- provider: NuGet + api_key: + secure: NlJ+D6kXfgU6RgRuf9okylLDENp8DA3tTRSC6UHBNbRS9ZAvRrC3Z0++Mr5VtGvz + on: + branch: release/v4 diff --git a/clean.bat b/clean.bat new file mode 100644 index 0000000000..b8b7e8be43 --- /dev/null +++ b/clean.bat @@ -0,0 +1,4 @@ +@echo off +SET root=%~dp0 +powershell -NoProfile "%root%/Build/Clean.ps1" +if %errorlevel% neq 0 exit /b %errorlevel% \ No newline at end of file diff --git a/generate-code.bat b/generate-code.bat index b005b957fe..27672eeda9 100644 --- a/generate-code.bat +++ b/generate-code.bat @@ -1,3 +1,5 @@ @echo off SET scriptdir=%~dp0 -powershell -ExecutionPolicy Bypass -NoProfile -File "%scriptdir%UnitsNet\Scripts\GenerateUnits.ps1" +pushd "%scriptdir%UnitsNet\Scripts\ +powershell -ExecutionPolicy Bypass -NoProfile -File ".\GenerateUnits.ps1" +popd diff --git a/test.bat b/test.bat new file mode 100644 index 0000000000..cddb2d7d07 --- /dev/null +++ b/test.bat @@ -0,0 +1,5 @@ +@echo off +SET root=%~dp0 + +powershell -NoProfile %root%/Build/Test.ps1 +if %errorlevel% neq 0 exit /b %errorlevel% \ No newline at end of file